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();
        }
    };
  • 相关阅读:
    jmeter_响应断言与xpath assertion
    jmeter查看结果树_各种方式
    HTTP request/respond详解及响应状态码
    LINUX常用命令笔记1
    什么是接口以及接口测试
    jmeter关联——正则表达式笔记
    BeautifulReport报告
    小白笔记:Git入门之常见命令
    Apache+Php+Mysql配置
    linux搭建jenkins+github详细步骤
  • 原文地址:https://www.cnblogs.com/grandyang/p/5600265.html
Copyright © 2011-2022 走看看