前中,中后,层中的排序还原成二叉树

本文介绍了一种通过中序遍历和层次遍历序列构建二叉树的算法,并提供了具体的C语言实现代码及运行结果。
比如树是这样的  
                                      1  
                                  /                                     8           4  
                              /   /       /  
                            2       5   7  
                          /                                 6               3  
   
  中序遍历6   2   8   5   3   1   7   4  
  层次遍历1   8   4   2   5   7   6   3 
设中许遍历的序列是a[i],按层次遍历的序列是b[i]  
  首先找b[1]在ai中出现的位置,设为a[j],也就是根结点  
  再找b[2..n]在a[i]中出现的位置,如果在a[j]的左边则是根节点的左子树中的节点  
  否则为右子树的节点  
  在找b[2]在a[i]中的位置,设为a[j1],就是根节点的第一个子树的根  
  在找b[3..n]在a[i]中的位置如果在a[j1]的左边则是a[j1]的左子树,否则为右子树  
  以此类推,每个节点的父子关系都找出来了,树就构造出来了
只要除了中序之外的排序中,父亲的排序在儿子前面,那么这个算法就有效
#include<stdio.h>  
  
void   main()   {  
  
int   a[]={6,2,8,5,3,1,7,4};  
  
int   b[]={1,8,4,2,5,7,6,3};  
  
int   parent[9]={0},mark[9]={0};  
  
int   i,j,k;  
  
for   (i=0;i<8;i++)   {  
  
for   (j=0;j<8;j++)    
  
if   (a[j]==b[i])   {mark[j]=1;break;}  
  
for   (k=j-1;k>=0   &&   !mark[k];k--)    
  parent[a[k]]
=a[j];  
  
for   (k=j+1;k<8   &&   !mark[k];k++)  
  parent[a[k]]
=-a[j];  
  }
  
  
for   (i=1;i<=8;i++)  
  
if   (parent[i]==0)   printf("%d   is   the   root. ",i);  
  
else    
  
if   (parent[i]>0)   printf("%d   is   the   left   child   of   %d. ",i,parent[i]);  
  
else   printf("%d   is   the   right   child   of   %d. ",i,-parent[i]);  
  }
   
  运行结果:  
  1   is   the   root.  
  2   is   the   left   child   of   8.  
  3   is   the   right   child   of   5.  
  4   is   the   right   child   of   1.  
  5   is   the   right   child   of   8.  
  6   is   the   left   child   of   2.  
  7   is   the   left   child   of   4.  
  8   is   the   left   child   of   1.  
   
  如果不是从1开始连续的数字的话,可以先编好序号,动态生成节点,parent数组用指针实现  
  有什么不对的地方请指正  
   
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值