0
点赞
收藏
分享

微信扫一扫

算法【树】 | 【栈用法】如何快速搞懂前序、中序、后序遍历?

就是耍帅 2022-02-05 阅读 63

文章目录

一、树的遍历

🐱‍👓树的详细介绍

1.1 先序遍历

在这里插入图片描述

1.2 中序遍历

在这里插入图片描述

1.3 后序遍历

在这里插入图片描述

1.4 代码

/*----------------------------------------------------------------------
	> File Name: treeTraverseByStack.cpp
	> Author: Jxiepc
	> Mail: Jxiepc
	> Created Time: Sat 05 Feb 2022 03:51:47 PM CST
----------------------------------------------------------------------*/
#include <iostream>
#include <stack>
struct tree {
    int val;
    struct tree *right;
    struct tree *left;
};

typedef tree treeNode;

/***************************栈****************************/
/** 前序遍历 */
void preForeachBystack(treeNode *head) {
    std::cout << "前序遍历:";
    if(head != nullptr) {
        std::stack<treeNode *> s;
        s.push(head);
        while(!s.empty()) {
            std::cout << s.top()->val << " ";
            head = s.top();
            s.pop();
            if(head->right != nullptr)
                s.push(head->right);
            if(head->left != nullptr)
                s.push(head->left);
        }
    }
    std::cout << std::endl;
}

/** 中序遍历 */
void midForeachBystack(treeNode *head) {
    std::cout << "中序遍历:";
    if(head != nullptr) {
        std::stack<treeNode *> s;
        while(!s.empty() || head != nullptr) {
            if(head != nullptr){
                s.push(head);
                head = head->left;
            } else {
                std::cout << s.top()->val << " ";
                head = s.top()->right;
                s.pop();
            }
        }
    }
    std::cout << std::endl;
}

/** 后序遍历 */
void backForeachBystack(treeNode *head) {
    std::cout << "后序遍历:";
    if(head != nullptr) {
        std::stack<treeNode *> s, s1;
        s.push(head);
        while(!s.empty()) {
            head = s.top();
            s1.push(head);
            s.pop();
            if(head->left != nullptr)
                s.push(head->left);
            if(head->right != nullptr)
                s.push(head->right);
        }
        while(!s1.empty()) {
            std::cout << s1.top()->val << " ";
            s1.pop();
        }
    }
    std::cout << std::endl;
}

void testForeachByS() {

    treeNode n1= {1, nullptr, nullptr};
    treeNode n2= {2, nullptr, nullptr};
    treeNode n3= {3, nullptr, nullptr};
    treeNode n4= {4, nullptr, nullptr};
    treeNode n5= {5, nullptr, nullptr};
    treeNode n6= {6, nullptr, nullptr};
    treeNode n7= {7, nullptr, nullptr};

    n1.left = &n2;
    n1.right = &n3;
    n2.left = &n4;
    n2.right = &n5;
    n3.left = &n6;
    n3.right = &n7;

    preForeachBystack(&n1);
    midForeachBystack(&n1);
    backForeachBystack(&n1);
}

int main(int argc, char* argv[])
{
    testForeachByS();

    return 0;
}


在这里插入图片描述

举报

相关推荐

0 条评论