LeetCode100 鐩稿悓鐨勬爲

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode100 鐩稿悓鐨勬爲相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/pre' title='pre'>pre   ==   鎬濇兂   return   leetcode   tac   span   淇濆瓨   bsp   

缁欏畾涓や釜浜屽弶鏍戯紝缂栧啓涓€涓嚱鏁版潵妫€楠屽畠浠槸鍚︾浉鍚屻€?/p>

濡傛灉涓や釜鏍戝湪缁撴瀯涓婄浉鍚岋紝骞朵笖鑺傜偣鍏锋湁鐩稿悓鐨勫€硷紝鍒欒涓哄畠浠槸鐩稿悓鐨勩€?/p>

绀轰緥 1:

杈撳叆:       1         1
          /        /          2   3     2   3

        [1,2,3],   [1,2,3]

杈撳嚭: true

绀轰緥 2:

杈撳叆:      1          1
          /                    2             2

        [1,2],     [1,null,2]

杈撳嚭: false

绀轰緥 3:

杈撳叆:       1         1
          /        /          2   1     1   2

        [1,2,1],   [1,1,2]

杈撳嚭: false




/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/*
绠楁硶鎬濇兂锛?
    閲囩敤閫掑綊锛岄€掑綊姣旇緝涓ゆ5鏍戝嵆鍙€?
*/
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(!p && !q)
            return true;
        if((!p&&q)||(p&&!q)||(p->val!=q->val))
            return false;
        return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
    }
};
/*
绠楁硶鎬濇兂锛?
    閲囩敤杩唬锛屽埄鐢ㄦ爤淇濆瓨缁撶偣鐒跺悗姣旇緝缁撶偣鍗冲彲銆?
*/
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        stack<TreeNode*> s1, s2;
        if (p)  s1.push(p);
        if (q)  s2.push(q);
        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.size() == s2.size();
    }
};

 

以上是关于LeetCode100 鐩稿悓鐨勬爲的主要内容,如果未能解决你的问题,请参考以下文章

#10115 銆屼竴鏈€?4.1 渚?3銆嶆牎闂ㄥ鐨勬爲

Leetcode-002-涓ゆ暟鐩稿姞

鐩稿鍐呭瓨鐨勬枃浠舵搷浣滃瓧鑺傛祦

鍒嗗竷寮忎簨鍔$殑CAP鐞嗚

銆婃垜鏄竴鍙狪T灏忓皬楦熴€嬭鍚庢劅

Java浠庡皬鐧藉埌鍏ラ棬锛孌ay4锛堟暟缁勶級