100. Same Tree

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.


给定两个二叉树,判断他们是否一样(结构一样,且相应节点的值相等)。

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;
    }

递归方法需要有出口,方法体的第一行为出口;当需要判断两个二叉树的结构不一样的时候我本打算这样写

  if( (p !=null && q == null) || (p ==null && q != null) ) return 

这个写法实际上有些多余,因为第一行已经过滤掉了都为空的节点,着两种写法是等价的

(p !=null && q == null) || (p ==null && q != null)  等价(p==null || q == null) 
原文地址:https://www.cnblogs.com/wxshi/p/7691150.html