首页 > 其他 > 详细

Same Tree

时间:2014-08-01 13:48:11      阅读:278      评论: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) {
        int flag = 1;/*标识两棵树是否一样*/
        _isSameTree_core(p, q, flag);
        return flag;
    }
    void _isSameTree_core(TreeNode *p, TreeNode *q, int &flag) {
        if (!p && !q)
            return;
        else if ((!p && q) || (p && !q) || (p->val != q->val)) {
            flag = 0;
            return;
        } else if (p && q) {
            _isSameTree_core(p->left, q->left, flag);
            _isSameTree_core(p->right, q->right, flag);
        }
    }
};


Same Tree,布布扣,bubuko.com

Same Tree

原文:http://blog.csdn.net/wan_hust/article/details/38333389

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