二叉树三种遍历的递归与非递归实现

#include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct TreeNode{
    long val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(long v){
        val = v;
        left = NULL;
        right = NULL;
    }
};

void maketree(TreeNode* root, long cnt){
    if(cnt == 0) return;
    long p, l, r;
    cin>>p>>l>>r;
    if(l){
        root->left = new TreeNode(l);
        maketree(root->left, cnt - 1);
    }
    if(r){
        root->right = new TreeNode(r);
        maketree(root->right, cnt - 1);
    }
}

void preorder(TreeNode* root, vector<long>& res){
    if(!root) return;
    res.push_back(root->val);
    preorder(root->left, res);
    preorder(root->right, res);
}

void midorder(TreeNode* root, vector<long>& res){
    if(!root) return;
    midorder(root->left, res);
    res.push_back(root->val);
    midorder(root->right, res);
}

void postorder(TreeNode* root, vector<long>& res){
    if(!root) return;
    postorder(root->left, res);
    postorder(root->right, res);
    res.push_back(root->val);
}

void print(const vector<long>& res){
    for(auto num: res) cout << num << " ";
    cout << endl;
}

void preorder_1(TreeNode* root, vector<long>& res){
    if(!root) return;
    stack<TreeNode*> s;
    s.push(root);
    while(!s.empty()){
        TreeNode* tmp = s.top();
        s.pop();
        res.push_back(tmp->val);
        if(tmp->right) s.push(tmp->right);
        if(tmp->left) s.push(tmp->left);
    }
}

void midorder_1(TreeNode* root, vector<long>& res){
    if(!root) return;
    stack<TreeNode*> s;
    TreeNode* cur = root;
    
    while(cur || !s.empty()){
        while(cur){
            s.push(cur);
            cur = cur->left;
        }
        TreeNode* tmp = s.top();
        res.push_back(tmp->val);
        s.pop();
        cur = tmp->right;
    }
}

void postorder_1(TreeNode* root, vector<long>& res){
    if(!root) return;
    stack<TreeNode*> s;
    s.push(root);
    while(!s.empty()){
        TreeNode* tmp = s.top();
        res.push_back(tmp->val);
        s.pop();
        if(tmp->left) s.push(tmp->left);
        if(tmp->right) s.push(tmp->right);
    }
    
    for(long i = 0; i < res.size() / 2; i++){
        long tmp = res[i];
        res[i] = res[res.size() - i - 1];
        res[res.size() - i - 1] = tmp;
    }
}
int main(){
    long N, root_val;
    cin >> N >> root_val;
    TreeNode* root = new TreeNode(root_val);
    maketree(root, N);
    vector<long> res;
    preorder_1(root, res);
    print(res);
    res.clear();
    midorder_1(root, res);
    print(res);
    res.clear();
    postorder_1(root, res);
    print(res);
    res.clear();
    return 0;
    
}

  

posted @ 2020-01-20 11:58  PirateLHX  阅读(140)  评论(0编辑  收藏  举报