比如树是这样的
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数组用指针实现
有什么不对的地方请指正
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数组用指针实现
有什么不对的地方请指正
本文介绍了一种通过中序遍历和层次遍历序列构建二叉树的算法,并提供了具体的C语言实现代码及运行结果。
631

被折叠的 条评论
为什么被折叠?



