您的位置:首页 > 其它

通过中序遍历、后序遍历求先序遍历

2017-05-06 18:07 246 查看


 用上图二叉树作为一个例子
中序遍历:8 4 9 2 10 5 1 6 3 7
后序遍历:8 9 4 10 5 2 6 7 3 1

1.首先我们通过后序遍历寻找整颗二叉树的根结点,由于后序遍历的特点为  “左右根 ”,所以后边遍历的最后一个值便是根节点的值,根节点值为1
2.由于中序遍历的特点为“左根右”,我们知道了根节点后,便可以推出根节点的左子树与右子树
3.在左子树中递归刚才的过程
4.在右子树中递归刚才的过程

所以在上图树中,我们先找到了根节点为1,然后左子树中序遍历为8 4 9 2 10 5  ,左子树后序遍历为 8 9 4 10 5 2,我们又找到了左子树的根节点为2,然后左子树的左子树中序遍历便为8 4 9……(以此类推,递归算法)

通过中序遍历、后序遍历 输出先序遍历,下面的代码在解决过程中未建立二叉树。

#include<stdio.h>
#include<stdlib.h>
void fun(char*inorder, char*postorder, int length)
{
if (length == 0)
return;
int rootindex = 0;
for (; rootindex < length; rootindex++)
if (inorder[rootindex] == postorder[length - 1])
break;
printf("%c", inorder[rootindex]);
fun(inorder, postorder, rootindex);
fun(inorder + rootindex+1, postorder+rootindex, length - rootindex-1);
}

int main()
{
int length;
printf("请输入二叉树的结点数:");
scanf("%d",&length);
getchar();
char*Inordertree;//中序
char *Postordertree;//后序
Inordertree = (char*)malloc(length*sizeof(char));
Postordertree = (char*)malloc(length*sizeof(char));
int i;
printf("请输入二叉树的中序遍历(回车结束)");
for (i = 0; i < length; i++)
scanf("%c",&Inordertree[i]);
getchar();
printf("请输入二叉树的后序遍历(回车结束)");
for (i = 0; i < length; i++)
scanf("%c",&Postordertree[i]);
getchar();
printf("二叉树的先序遍历为:");
fun(Inordertree, Postordertree, length);
printf("\n");
system("pause");
return 0;
}


效果展示(10用A代替)






通过先序遍历、中序遍历求后序遍历 方法与此类似。

如果希望建立二叉树,那么上述方法可以给你提供一点点小思路~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐