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

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

#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <vector>
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<BT> 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<BT> 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<vector<int>> levelorder(BT root) {
    
    
    queue<BT> que;
    que.push(root);
    vector<vector<int>> ans;
    while(!que.empty()) {
    
    
        int n = que.size();
        vector<int> tmp;
        for(int i=0; i<n; 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<ans.size(); i++) {
    
    
        for(int j=0; j<ans[i].size(); j++)
            cout << ans[i][j] << ' ';
        cout << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/ayitime/article/details/126001100