判断是否为相同树
题:给出两个二叉树,写一个函数判断是否相同(结构和对应的值都相同)
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
思路:这道题最直接的思路是递归,这和二叉树的遍历很相似。
代码:
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);
}
}
时间复杂度:O(N),空间复杂度:O(log(N)),N是二叉树节点的数目