首页 > 其他 > 详细

【LeetCode】Same Tree

时间:2014-10-25 23:05:55      阅读:528      评论: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.


      思路:

      考察递归。判断两棵树相等,只要递归判断两棵树的结构和值。所以遇到一个指针为空的时候,另一个指针一定要为空。不为空的时候,两个指针的值必须相等。再递归左右子树是否相等。


      代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
		bool flag = true;

		/* 其中一个为空,则肯定结束 */
		if(p == NULL || q == NULL)
		{
			/* 两个都为空才是相等的 */
			if(p == NULL && q == NULL)
				return true;
			return false;
		}

		/* 两个节点的值不等则 false */
		if(p->val != q->val) return false;

		/* 递归判断左子树 */
		flag = flag & isSameTree(p->left,q->left);

		/* 递归判断右子树 */
		flag = flag & isSameTree(p->right,q->right);

		return flag;
    }
};

【LeetCode】Same Tree

原文:http://blog.csdn.net/jcjc918/article/details/39898499

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