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

【Same Tree】cpp

时间:2015-05-15 09:01:13      阅读:145      评论: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 a binary tree node.
 * 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) {
        if ( !p && !q ) return true;
        stack<TreeNode *> sta_p,sta_q;
        if (p) sta_p.push(p);
        if (q) sta_q.push(q);
        while ( !sta_p.empty() && !sta_q.empty() ){
            TreeNode * tmp_p = sta_p.top();
            sta_p.pop();
            TreeNode * tmp_q = sta_q.top();
            sta_q.pop();
            // node val
            if ( tmp_p->val==tmp_q->val ){
                // right child
                if ( tmp_p->right && tmp_q->right ){
                    sta_p.push(tmp_p->right);
                    sta_q.push(tmp_q->right);
                }
                else if ( !tmp_p->right && !tmp_q->right )
                {}
                else{ return false; }
                // left child
                if ( tmp_p->left && tmp_q->left ){
                    sta_p.push(tmp_p->left);
                    sta_q.push(tmp_q->left);
                }
                else if ( !tmp_p->left && !tmp_q->left )
                {}
                else{ return false; }
            }
            else { return false; }
        }
        return sta_p.empty() && sta_q.empty();
    }
};

tips:

二叉树先序遍历。

1. 比较节点val

2. 比较节点right child

3. 比较节点left child

========================

学习了一个更简洁版的代码,主要简洁的地方是入栈时候不需要判断为NULL。

代码:

/**
 * Definition for a binary tree node.
 * 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) {
        stack<TreeNode *> sta_p,sta_q;
        sta_p.push(p);
        sta_q.push(q);
        while ( !sta_p.empty() && !sta_q.empty() )
        {
            p = sta_p.top();
            sta_p.pop();
            q = sta_q.top();
            sta_q.pop();
            if ( !q && !p ) continue;
            if ( !q || !p ) return false;
            if ( p->val!=q->val ) return false;
            sta_p.push(p->right);
            sta_p.push(p->left);
            sta_q.push(q->right);
            sta_q.push(q->left);
        }
        return sta_p.empty() && sta_q.empty();
    }
};

【Same Tree】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4505032.html

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