码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode -- Same Tree

时间:2015-10-31 11:39:46      阅读:110      评论: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.


比较两个二叉树是否完全相同。


思路:
直接对两个树从根节点同时DFS,使用全局成员来记录是否相等即可。




实现代码:






/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public bool IsSameTree(TreeNode p, TreeNode q) 
    {
        CompareTree(p, q);
    	return _same;
    }
private bool _same = true;
private void CompareTree(TreeNode p , TreeNode q)
{
	if(!_same){
		return;
	}
	
	if(p == null && q == null){
		return ;
	}
	if(p == null && q != null || q == null && p != null || p.val != q.val){
		_same = false;
		return;
	}
	CompareTree(p.left, q.left);
	CompareTree(p.right, q.right);
}


}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode -- Same Tree

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/49531135

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!