L2-011. 玩转二叉树

#include <cstdio>
#include <vector>
#include <list>
#include <iostream>
using namespace std;
vector<int> in, pre;
struct Node
{
    int data;
    struct Node* left, *right;
    Node()
    {
        left = NULL;
        right = NULL;
    }
};

list<Node*> chainList;
void createTree(Node* &node, int data)
{
    node = new Node();
    node->data = data;
}


void levelorder(Node* &node, int root, int start, int end)
{
    if(start > end) return ;
    int i = start;
    while(i < end && in[i] != pre[root]) i++;
    createTree(node, pre[root]);
    levelorder(node->left, root + 1, start, i - 1);
    levelorder(node->right, root + 1 + i - start, i + 1, end);
}

void print()
{
    Node* node;
    while(!chainList.empty())
    {
        node = chainList.back();
        chainList.pop_back();
        cout << " " << node->data;
        if(node->right!=NULL)
            chainList.push_front(node->right);
        if(node->left!=NULL)
            chainList.push_front(node->left);
    }
}
int main()
{
    Node* root;
    int n, cnt = 0;
    scanf("%d", &n);
    in.resize(n);
    pre.resize(n);
    for(int i = 0; i < n; i++) scanf("%d", &in[i]);
    for(int i = 0; i < n; i++) scanf("%d", &pre[i]);
    levelorder(root, 0, 0, n-1);
    if(root!=NULL)
    {
        cout << root->data;
        if(root->right!=NULL)
            chainList.push_front(root->right);
        if(root->left!=NULL)
            chainList.push_front(root->left);
    }
    print();
    return 0;
}

 

posted @ 2017-08-28 17:05  diamondDemand  阅读(200)  评论(0)    收藏  举报