Same Tree
Given two binary trees, write a function to check if they are equal or
-
Two binary trees are considered equal if they are structurally
-
and the nodes have the same value.
思路: recursion, 注意判断条件不应该 if(p.val == q.val) return true,因为这样后面没有比较就比较了当前层, 要确保比较到最底层 if (p == null && q == null) 再返回true;
时间复杂度: O(n) n为节点数
空间复杂度: O(h) h为树的高度
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
if (p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
关键字:tree, recursion, null, return