通过中序遍历、后序遍历求先序遍历
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代替)
通过先序遍历、中序遍历求后序遍历 方法与此类似。
如果希望建立二叉树,那么上述方法可以给你提供一点点小思路~
相关文章推荐
- LeetCode之通过二叉树的中序遍历和后序遍历还原二叉树
- 二叉树非递归先序遍历、中序遍历、后序遍历
- 二叉树的创建、前序遍历、中序遍历、后序遍历
- 二叉树的创建、前序遍历、中序遍历、后序遍历
- pat甲1119. Pre- and Post-order Traversals (已知前序和后序遍历求中序遍历)
- 实现二叉树的先序遍历、中序遍历、后序遍历的递归非递归算法以及层次遍历算法
- uva 439 前序,中序遍历 转化成后序遍历 不用指针!用数组
- C++数据结构--二叉树的前序遍历,中序遍历,后序遍历
- 用Java实现二叉树前序遍历、中序遍历和后序遍历。
- c++实现二叉树的先序遍历,中序遍历,后序遍历(递归方法)及运行实例结果
- 二叉树创建、前序遍历、中序遍历、后序遍历 的 递归与非递归实现 以及 层次遍历
- 数据结构之二叉树的前序遍历、中序遍历、后序遍历、层序遍历
- 二叉树前序、中序遍历得到后序遍历
- Leetcode - Tree - 106. Construct Binary Tree from Inorder and Postorder Traversal(根据中序遍历和后序遍历重构二叉树)
- 给定二叉树的先序遍历中序遍历,求后序遍历
- 二叉树的创建、前序遍历、中序遍历、后序遍历
- 二叉树系列(1)已知二叉树的中序遍历和前序遍历,如何求后序遍历
- Tree UVA - 548 已知中序遍历和后序遍历,求这颗二叉树。
- 数据结构之二叉树的前序遍历、中序遍历、后序遍历、层序遍历
- 用Java实现二叉树前序遍历、中序遍历和后序遍历。