首页 > 其他 > 详细

leetcode_100_Same Tree

时间:2015-03-24 14:49:39      阅读:130      评论: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.

思路:

由于这题标识为easy,判断两棵树是否相等,想到了用递归。有这几种可能,两棵树相等的充要条件为root的值相等&&左子树相等&&右子树相等,两棵树都为空时也相等,其中一棵为空时就不相等

代码:

class TreeNode{
		int val;
		TreeNode left;
		TreeNode right;
		TreeNode(int x){val=x;}
	}
	public boolean isSameTree(TreeNode p, TreeNode q) {
		if(p==null&&q==null)//两棵树都为空时相等
			return true;
		if(p==null||q==null)//其中一棵为空时就不相等
			return false;
		//root的值相等&&左子树相等&&右子树相等
        if(p.val==q.val&&isSameTree(p.left, q.left)&&isSameTree(p.right, q.right))
			return true;
        return false;
    }

结果:

技术分享

leetcode_100_Same Tree

原文:http://blog.csdn.net/mnmlist/article/details/44591099

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