首页 > 其他 > 详细

leetcode 100.Same Tree

时间:2015-03-02 18:48:00      阅读:151      评论:0      收藏:0      [点我收藏+]

这道题目我最初想的太多了,导致做了好久,之后从网上一看,一下醒悟过来,不难。

题目:

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

 

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

leetcode 100.Same Tree

原文:http://www.cnblogs.com/Pillar/p/4309031.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!