leetcode Daily Challenge on July 13th, 2020.
leetcode-cn Daily Challenge on August 7th, 2020.
Difficulty : Easy
Related Topics : DFS、Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true
Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false
- mine
- Java
- DFS & Recursion
Runtime: 0 ms, faster than 100.00%, Memory Usage: 38.7 MB, less than 11.47% of Java online submissions
// O(N)time // O(D)space public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null) return q == null; if(q == null) return p == null; return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }
- DFS & Recursion
- Java