后序中序建立二叉树

本文介绍了一种通过后序遍历和中序遍历序列构建二叉树的方法,并提供了完整的C++实现代码。该方法首先读取输入的遍历序列,然后递归地构建二叉树,并最终以先序遍历的方式输出构建好的二叉树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
using namespace std;

char post[20],ins[20];
typedef struct BiTNode
{
 char data;
 struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

BiTree Build_tree(int post_begin,int post_end,int in_begin,int in_end)
{
 int i,left_tree_len,right_tree_len;
 BiTree root;
 root = (BiTNode*)malloc(sizeof(BiTNode));
 if (root)
 {
  root->data = post[post_end];
  i = in_begin;
  while (ins[i] != root->data)
  {
   i++;
  }
  left_tree_len = i - in_begin;
  right_tree_len = in_end - i;
  if (left_tree_len)
  {
   BiTree left_root = Build_tree(post_begin,post_begin + left_tree_len - 1,
                              in_begin,in_begin + left_tree_len - 1);
   root->lchild = left_root;
  }
  else
   root->lchild = NULL;  //很重要
  if (right_tree_len)
  {
   BiTree right_root = Build_tree(post_end - right_tree_len,post_end - 1,
                              in_end - right_tree_len + 1,in_end);
   root->rchild = right_root;
  }
  else
   root->rchild = NULL;
  return root;
 }
 else
  return NULL;
}

void visit(char data)
{
 printf("%c ",data);
}

void Preorder(BiTree T) //先序
{
 if (T)
 {
  visit(T->data);
  Preorder(T->lchild);
  Preorder(T->rchild);
 }
}

void main() 
{
 cout<<"请输入后序遍历序&中序遍历序列:"<<endl;
 cin>>post;
 cin>>ins;
 int i = 0;
 while (post[i] != '#')
  i++;
 BiTree bt = Build_tree(0,i - 1,0,i - 1);
 Preorder(bt);
 printf("\n");
}

/*
请输入后序遍历序&中序遍历序列:
DFECBKJHIGA#
BDCEFAHJKGI#
A B C D E F G H J K I
*/


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值