第5章:LeetCode--算法:DFS-BFS深度优选遍历和广度优先遍历(3)

https://www.jianshu.com/p/b086986969e6

DFS--需要借助stack实现 stack.push stack.pop

BFS--需要借助队列queue

stack-->先进后出, queue-->先进先出

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();
}

 

前序遍历(root->left->right)、中序遍历(left->root->right)、后序遍历(left->right->root),指root节点访问顺序。

上一篇:02.栈(基于数组)


下一篇:JAVA自己实现List接口Stack