重建二叉树

题目:给定二叉树的先序和中序遍历,构建这个二叉树。例如:先序遍历结果是:abdcef,中序遍历的结果是:dbaecf,如何构建二叉树。

分析:先序遍历的结果中的每一个节点,将中序遍历的结果分为左右子树两部分,递归构建二叉树,就可以完成树得构建。

#include <stdio.h>
#include <stdlib.h>
#define N 6
typedef struct node{
    char ch;
    struct node *left;
    struct node *right;
}*node_ptr;

char pre[]={'a','b','d','c','e','f'};
char in[]={'d','b','a','e','c','f'};

node_ptr 
build_tree(int pre_start,int pre_end,int in_start,int in_end)
{
    char root_value = pre[pre_start];
    int pre_left_end,length,in_root;
    node_ptr root = (node_ptr)malloc(sizeof(struct node));
    if(root){
        root->ch = root_value;
        root->left = root->right = NULL;
    }else
        exit(1);

    if(pre_start == pre_end){
        if(in_start == in_end && pre[pre_start] == in[in_start])
            return root; 
        else
            exit(1);
    }
    in_root = in_start;
    while(in_root <= in_end && in[++in_root] != root_value)
        ;
    if(in_root == in_end && in[in_root] != root_value)
        exit(1);
    length = in_root - in_start;
    pre_left_end = pre_start + length;
    if(length > 0)
        root->left = build_tree(pre_start+1,pre_left_end,in_start,in_root-1);
    if(length < pre_end - pre_start)
        root->right = build_tree(pre_left_end + 1,pre_end,in_root + 1,in_end);
    return root;
}

void pre_print(node_ptr root){
    if(root == NULL)
        return;
    printf("%c\n",root->ch);
    pre_print(root->left);
    pre_print(root->right);
}

void in_print(node_ptr root){
    if(root == NULL)
        return;
    in_print(root->left);
    printf("%c\n",root->ch);
    in_print(root->right);
}

int main(){
    node_ptr root = build_tree(0,N-1,0,N-1);
    pre_print(root);    
    printf("\n");
    in_print(root);
   return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值