[LintCode] Identical Binary Tree 相同二叉树

简介:

Check if two binary trees are identical. Identical means the two binary trees have the same structure and every identical position has the same value.

1             1
/ \           / \
2   2   and   2   2
/             /
4             4

are identical.

1             1
/ \           / \
2   3   and   2   3
/               \
4                 4

are not identical.

LeetCode上的原题,请参见我之前的博客Same Tree

解法一:

class Solution {
public:
    /**
     * @aaram a, b, the root of binary trees.
     * @return true if they are identical, or false.
     */
    bool isIdentical(TreeNode* a, TreeNode* b) {
        if (!a && !b) return true;
        if (!a || !b) return false;
        return a->val == b->val && isIdentical(a->left, b->left) && isIdentical(a->right, b->right);
    }
};

解法二:

class Solution {
public:
    /**
     * @aaram a, b, the root of binary trees.
     * @return true if they are identical, or false.
     */
    bool isIdentical(TreeNode* a, TreeNode* b) {
        stack<TreeNode*> s1, s2;
        if (a) s1.push(a); 
        if (b) s2.push(b);
        while (!s1.empty() && !s2.empty()) {
            TreeNode *t1 = s1.top(); s1.pop();
            TreeNode *t2 = s2.top(); s2.pop();
            if (t1->val != t2->val) return false;
            if (t1->left) s1.push(t1->left);
            if (t2->left) s2.push(t2->left);
            if (s1.size() != s2.size()) return false;
            if (t1->right) s1.push(t1->right);
            if (t2->right) s2.push(t2->right);
            if (s1.size() != s2.size()) return false;
        }
        return s1.empty() && s2.empty();
    }
};

 本文转自博客园Grandyang的博客,原文链接:相同二叉树[LintCode] Identical Binary Tree ,如需转载请自行联系原博主。

相关文章
|
6月前
Leetcode Binary Tree Postorder Traversal(面试题推荐)
非递后续归遍历二叉树,肯定得用到栈。先序遍历很好写,但后续遍历就不是那么容易了。 只需要设置个指针pre,指向最后输出的那个节点就行了,只要判断cur指针指向的是上次输出节点的父节点,且cur无其他未遍历的节点,这个时候就把cur节点输出即可,然后更改pre。原理是要遍历当前节点,其所有子节点都必须遍历完,因为肯定是先左后右,所以只需一个指针保持前一次输出的结果即可。
22 0
LeetCode 100. Same Tree
此题目是给定两棵树,判断两个树是否相等.
51 0
LeetCode 100. Same Tree
|
C++ Python
LeetCode 965. Univalued Binary Tree
LeetCode 965. Univalued Binary Tree
67 0
LeetCode 965. Univalued Binary Tree