LeetCode -- 100. Same Tree

Posted feliz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode -- 100. Same Tree相关的知识,希望对你有一定的参考价值。

// Recursively
bool isSameTree1(TreeNode* p, TreeNode* q) 
    if (p && q)
        return p->val==q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    return p == q;


// BFS + queue
bool isSameTree(TreeNode* p, TreeNode* q) 
    queue<pair<TreeNode*, TreeNode*>> myQueue;
    myQueue.push(pair<TreeNode*, TreeNode*>(p, q));
    while (!myQueue.empty()) 
        p = myQueue.front().first;
        q = myQueue.front().second;
        if(!p ^ !q || (p && q && p->val != q->val))
            break;
        myQueue.pop();
        if(p && q) 
            myQueue.push(pair<TreeNode*, TreeNode*>(p->left, q->left));
            myQueue.push(pair<TreeNode*, TreeNode*>(p->right, q->right));
        
    
    return myQueue.empty();


// DFS + stack
bool isSameTree3(TreeNode* p, TreeNode* q) 
    stack<pair<TreeNode*, TreeNode* >> myStack;
    myStack.push(pair<TreeNode*, TreeNode*>(p, q));
    while (!myStack.empty()) 
        p = myStack.top().first;
        q = myStack.top().second;
        if (!p ^ !q || (p && q && p->val != q->val))
            break;
        myStack.pop();
        if (p && q) 
            myStack.push(pair<TreeNode*, TreeNode*> (p->right, q->right));
            myStack.push(pair<TreeNode*, TreeNode*> (p->left, q->left));
        
    
    return myStack.empty();

  

以上是关于LeetCode -- 100. Same Tree的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode[100]-Same Tree

[LeetCode]题解(python):100 Same Tree

小程序 - leetcode 100. Same Tree

LeetCode(100):Same Tree

leetcode-- 100. Same Tree

LeetCode笔记:100. Same Tree