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

Same Tree

时间:2014-08-01 13:48:11      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:des   io   for   问题   cti   ar   amp   ef   

问题描述:

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

标签:des   io   for   问题   cti   ar   amp   ef   

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

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