题目简介
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.
自己的解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null)
return true;
else if(q!=null&&p!=null&&p.val==q.val){
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
else{
return false;
}
}
}
else if(p.val==q.val)
一提交,就说我else if这一行java.lang.nullpointerexception。然后我就去查询了这个异常。
NullPointerException异常即为空指针异常,是因为用空(null)去调用属性或方法。 null表示没有这个对象,既然没有这个对象,那么去调用他的属性和方法,就会报异常。最好的处理方法是在这一句加上对变量是否为空的判断。我看了一下前面的语句,发现有的情况忘了考虑,就是当其中一个变量为空的时候,会进行else if操作,所以会有空指针异常,所以我改为这样
else if(p.val==q.val&&q!=null&&p!=null)
但是它还是报java.lang.nullpointerexception异常。这让我百思不得其解。最后想会不会是顺序的问题,所以我改为
else if(q!=null&&p!=null&&p.val==q.val)
这回成功通过。这次的问题让我对空指针异常,以及顺序的问题有了深刻的印象。在使用对象和其中的变量时一定要考虑,它是否有可能为空。然后就是if等等语句里面的顺序也很关键,在使用这类语句时,如果有很多的等式需要判断请考虑一下顺序是否会对它造成影响。
Hot解法
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 isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
return false;
}
Hot解法的思路大致与我们相同,也是使用递归的思想,这里不作分析。