zoukankan      html  css  js  c++  java
  • [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.

     
    Example
        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();
        }
    };
  • 相关阅读:
    bzoj1059: [ZJOI2007]矩阵游戏
    NEW
    bzoj2438: [中山市选2011]杀人游戏
    bzoj4554: [Tjoi2016&Heoi2016]游戏 二分图匹配
    【高精度】模板 (C++)
    【BZOJ4025】二分图 LCT
    读入/输出模板
    一些 Markdown 语法
    题解 P3732 [HAOI2017]供给侧改革
    题解 CF1598A Computer Game
  • 原文地址:https://www.cnblogs.com/grandyang/p/5600265.html
Copyright © 2011-2022 走看看