6-5(*) Build Tree from Post- and In-order Sequences (10 分)

6-5(*) Build Tree from Post- and In-order Sequences (10 分)

6-5(*) Build Tree from Post- and In-order Sequences (10 分)
You are supposed to write a function of constructing a binary tree with given postorder and inorder sequences.

Format of function:

Tree BuildTree( int inorder[], int postorder[], int N );

where Tree is defined as the following:

typedef struct TreeNode *Tree;
struct TreeNode {
    int Element;
    Tree  Left;
    Tree  Right;
};

The inorder and postorder sequences are stored in int inorder[] and int postorder[], respectively. The integer N is the number of nodes in the tree. The function BuildTree is supposed to return the pointer to the root of the constructed tree.

Sample program of judge:

#include <stdio.h>
#include <stdlib.h>

#define MAXN 10

typedef struct TreeNode *Tree;
struct TreeNode {
    int Element;
    Tree  Left;
    Tree  Right;
};

Tree BuildTree( int inorder[], int postorder[], int N );

void Inorder_output( Tree T ); /* details omitted */
void Postorder_output( Tree T ); /* details omitted */

int main()
{
    Tree T;
    int inorder[MAXN], postorder[MAXN], N, i;

    scanf("%d", &N);
    for (i=0; i<N; i++) scanf("%d", &inorder[i]);
    for (i=0; i<N; i++) scanf("%d", &postorder[i]);
    T = BuildTree(inorder, postorder, N);
    printf("Check:\n");
    Inorder_output(T);   printf("\n");
    Postorder_output(T); printf("\n");

    return 0;
}

/* Your function will be put here */

Sample Input:

7
1 2 3 4 5 6 7
2 3 1 5 7 6 4结尾无空行

Sample Output:

Check:
1 2 3 4 5 6 7 
2 3 1 5 7 6 4 结尾无空行

AC代码

Tree BuildTree( int inorder[], int postorder[], int N )
{
    if(N==0)
        return NULL;
    char rootValue = postorder[N-1];
    Tree root = (Tree*)malloc(sizeof(Tree));
    root->Element = rootValue;
    int leftSize;
    for(int i=0; i<N; i++)
    {
        if(inorder[i]==rootValue)
        {
            leftSize = i;
            break;
        }
    }
    root->Left = BuildTree(inorder,postorder,leftSize);
    for(int i=0;i<N-leftSize-1;i++)
    {
        inorder[i]=inorder[i+leftSize+1];
        postorder[i]=postorder[i+leftSize];
    }
    root->Right = BuildTree(inorder,postorder,N-leftSize-1);
    return root;

}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值