二叉树--中序遍历和后序遍历建树

传送门:Rebuild binary tree from sequences of infix order and post order

总Time Limit: 500ms Memory Limit: 65535kB
Description
We know how totravel along a binary tree in three kinds of depth-first order in order to getthe sequences of infix order, preorder and post order. The other way around, wecan build a binary tree with the sequences of infix order and post order orinfix order and preorder. Here the input is the sequences of infix order andpost order. You are required to build the binary tree in memory and output thesequence of preorder.
Every node isidentifier by an integer different from each other. For the binary tree below,
the sequence of infix order is 9 5 32 67
the sequence of post order is 9 32 67 5
and the sequence of preorder is 5 9 67 32.

Input
It’s two lines. The first line is the sequence of infix order and the second line is the sequence of post order. The numbers are separated by a blank space. The number is between 0 and 65535. Unreasonable input data are not taken into account for the time being.
Output
It is one line. It is the sequence of preorder of the binary tree rebuilt. The numbers are separated by a blank space.
Sample Input
9 5 32 67
9 32 67 5
Sample Output
5 9 67 32


分析:
后序最后一个元素是根节点,可以由此在中序中找到左右节点的分界处,递归建树。

/*
@Filename:      code.cpp
@Author:        wyl6 
@Mail:          ustbcs_wyl@163.com
思路:用后序找到根节点,然后用中序根据根节点找到左右子树,知道找到所有节点
*/
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const int MAXN = 1e5;
int inOrder[MAXN],postOrder[MAXN];
struct binaryNode
{
    int data;
    binaryNode *left,*right;
    binaryNode():data(0),left(NULL),right(NULL){}
};

binaryNode* BuildTree(int inB,int inE,int postB,int postE)
{
    int i = 0;
    binaryNode * root = new binaryNode();
    root->data = postOrder[postE];  //后序遍历序列中获取根节点
    while(inOrder[inB+i] != root->data) i++;//中序遍历序列中查找子树根节点位置
    if(i>0)//左子树存在
        root->left = BuildTree(inB,inB+i-1,postB,postB+i-1);
    if(inB+i//右子树存在
        root->right = BuildTree(inB+i+1,inE,postB+i,postE-1);
    return root;
}

void PreTravel(binaryNode * root)
{
    if(root == NULL) return;
    printf("%d ",root->data);
    PreTravel(root->left);
    PreTravel(root->right);
}

void DeleteTree(binaryNode * root)
{
    if(root == NULL) return;
    DeleteTree(root->left);
    DeleteTree(root->right);
    delete root;
}

int main()
{
    int i = 0;
    while(cin >> inOrder[i++]) //get到每次读入一行的新方法
        if(cin.get() != ' ') break;
    i = 0;
    while(cin >> postOrder[i++])
        if(cin.get() != ' ') break;
    binaryNode * root = BuildTree(0,i-1,0,i-1);
    PreTravel(root);
    DeleteTree(root);
    return 0;
}

你可能感兴趣的:(二叉树)