leetcode 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.

解决方案:Runtime: 191 ms

public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null&&q==null)
            return true;
        if(p!=null&&q==null || p==null&&q!=null){//here can be if(p == null || q == null){,but it will take more time
            return false;
        }
        if(p.val == q.val){
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }
        return false;
    }
}

总结:这道题目注意几个判断就好了,其他的就是单纯的递归。

原文地址:https://www.cnblogs.com/Pillar/p/4309031.html