题目:
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 binary tree
* 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){
if(p.val==q.val){
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
else return false;
}
else
return false;
}
}
出现的错误:
在(p.val==q.val)条件下,曾写成了
return isSameTree(p.left,q.left);
return isSameTree(p.right,q.right);
编译错误,unreachable statement。因为一个条件下,写了两个return啊!!!!
出现unreachable statement 错误的可能有:
(1)在reutrn语句后写语句。
(2)在throw语句后写语句。
(3)break、continue语句之后定义语句。
(4)“\u10100”//合法,相当于‘\u1010’和字符串“0”。
(5)移位运算符可以用于long int char short byte。
(6)类的访问控制符可以是public或什么都不加。
(7)goto是保留字但不是关键字。then什么都不是。
(8)把超类的类型强制转换后赋给子类的对象时,编译无异常,但运行时会出现异常。