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.
两个树完全相等要求节点完全相同且里面的值完全相同
因为只要p和q的某一个相同节点的值不相同就为假,而需要遍历完所有的点和值且都相等才为真,所以应该判断值的不同。
压栈思路:先左节点全入,然后左出右入。在压栈的过程中先后比较左右节点是否为空,并且比较值是否相等。
特殊情况:都为空树,则相等,只有一个为空树,则一定不相等。
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;
boolean left = isSameTree(p.left, q.left);
boolean right = isSameTree(p.right, q.right);
return left&&right;
}