栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【数据结构】 C++实现二叉树 先序、中序、后序、层序遍历

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构】 C++实现二叉树 先序、中序、后序、层序遍历

参考浙大陈越姥姥数据结构

#include 
#include 
#include 
#include 
#include 
using namespace std;


typedef struct t_node* BT;
struct t_node{
    int val;
    BT left;
    BT right;
};

BT insert_tree(int val) {
    BT node = new t_node;
    node->val = val;
    node->left = NULL;
    node->right = NULL;
    return node;
}

BT init_tree() {
    BT root = insert_tree(1);
    root->left = insert_tree(2);
    root->right =  insert_tree(3);
    root->left->left = insert_tree(4);
    root->left->right = insert_tree(5);
    root->right->left = insert_tree(6);
    root->right->right = insert_tree(7);

    return root;

}

void preOrder(BT root) {            // 递归遍历
    if(root) {
        preOrder(root->left);
        preOrder(root->right);
        cout << root->val << ' ';
    }
}

void preorder(BT root) {
    stack sta;
    while(root || !sta.empty()) {
        while(root) {
            sta.push(root);
            // cout << root->val << ' ';        // 非递归先序
            root = root->left;
        }
        if(!sta.empty()) {
            root = sta.top();
            cout << root->val << ' ';       // 非递归中序
            sta.pop();
            root = root->right;
        }
    }
}

void postorder(BT root) {           // 非递归后续
    stack sta;
    BT cur = root;
    BT last = NULL;
    while(cur) {
        sta.push(cur);
        cur=cur->left;
    }
    while(!sta.empty()) {
        cur = sta.top();
        sta.pop();
        if(cur->right==last || cur->right==NULL) {
            cout << cur->val << ' ';
            last = cur;
        }
        else {
            sta.push(cur);
            cur = cur->right;
            while(cur) {
                sta.push(cur);
                cur = cur->left;
            }
        }
    }
}

vector> levelorder(BT root) {
    queue que;
    que.push(root);
    vector> ans;
    while(!que.empty()) {
        int n = que.size();
        vector tmp;
        for(int i=0; i
            root = que.front();
            tmp.push_back(root->val);
            que.pop();
            // cout << root->val << ' ';
            if(root->left)
                que.push(root->left);
            if(root->right)
                que.push(root->right);
        }
        ans.push_back(tmp);
    }
    return ans;

}

int main()
{
    BT root = init_tree();
    // preOrder(root);
    // cout << endl;
    // preorder(root);
    // postorder(root);
    auto ans = levelorder(root);
    for(int i=0; i
        for(int j=0; j
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1025577.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号