Total Accepted: 102505
Total Submissions: 241539
Difficulty: Easy
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
Subscribe to see which companies asked this question
如题,判断两个二叉树是否是相同的:
思路是:判断其节点是否相同,然后再判断其子节点。
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==q){
if(isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)){
return true;
}
}
return false;
}
}
然而这种做法是不对的,因为节点p和q的引用是不同的,所以不能这样判断,造成的结果就是本来是相同的树,也会识别错误。 改正后
还是会报错:
if(p.val==q.val){
Line 14: java.lang.NullPointerException
好吧,空指针错误,于是,
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){
if(isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)){
return true;
}
}
return false;
}
}
世界安静了!