根据前序和中序便遍历构造完整二叉树,并输出层次遍历

#include <iostream>
#include <queue>


typedef struct node{
    char name;
    struct node* left;
    struct node* right;
    int _l;
    int _r;
    node(int l, int r) {
        _l = l;
        _r = r;
    }
    node(){}
} node;
void build(node* &root, std::string &pre, std::string &in, char ch, int l, int r);
void deletetree(node* root);
void postorder(node* root);
void order(std::queue<node*> &que);
int main() {
    node* root;
    std::string pre;
    std::string in;
    std::cin >> pre;
    std::cin >> in;
    std::queue<node*> que;
    build(root, pre, in, pre[0], 0, in.size());
    que.push(root);
    order(que);
      std::cout << std::endl;
    deletetree(root);
}
void order(std::queue<node*> &que) {
    if (que.size()) {
    std::cout << que.front()->name;
    if (que.front()->left)
        que.push(que.front()->left);
    if (que.front()->right)
        que.push(que.front()->right);
    que.pop();
    order(que);


    }
}
void postorder(node* root) {
    if (root->left)
        postorder(root->left);
    if (root->right)
        postorder(root->right);
    std::cout << root->name;
}
void deletetree(node* root) {
    if (root->left)
        deletetree(root->left);
    if (root->right)
        deletetree(root->right);
    delete root;
}
void build(node* &root, std::string &pre, std::string &in, char ch, int l, int r) {
    if (l != r) {
        root = new node;
        root->left = NULL;
        root->right = NULL;
        root->name = ch;
        int k;
        for (int i = l; i < r; i++)
            if (in[i] == ch)
                k = i;
        char lc = 0;
        char rc = 0;
        int min = pre.size();
        for (int i = l; i < k; i++) {
            for (int j = 0; j < pre.size(); j++) {
                if (in[i] == pre[j]) {
                    if (j < min)
                        min = j;
                    break;
                }
            }
        }
        if (min != pre.size()) {
            lc = pre[min];
        }
        min = pre.size();
        for (int i = k+1; i < r; i++) {
            for (int j = 0; j < pre.size(); j++) {
                if (in[i] == pre[j]) {
                    if (j < min)
                        min = j;
                }
            }
        }
        if (min != pre.size()) {
            rc = pre[min];
        }
        if (lc)
            build(root->left, pre, in, lc, l, k);
        if (rc)
            build(root->right, pre, in, rc,  k + 1, r);
    }
}

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/79660018