【树】已知二叉树前序和中序遍历求后序遍历,及中序和后序遍历求前序遍历

本文详细介绍了如何通过已知的二叉树中序遍历和后序遍历序列,推导出其前序遍历序列的方法。包括具体的算法实现和实例演示,旨在帮助读者理解和掌握二叉树遍历的相关概念。
#include<iostream>
using namespace std;
//已知二叉树前序遍历和中序遍历,求后序遍历
void binary_tree_postorder(char* preorder,char* inorder,int length){
	if (length == 0)
		return;
	char root = *preorder;
	int index = 0;
	for (; index < length; index++){
		if (inorder[index] == root)
			break;
	}
	binary_tree_postorder(preorder + 1, inorder, index);
	binary_tree_postorder(preorder + index + 1, inorder + index + 1, length - index - 1);
	cout << root << " ";
}
//已知二叉树中序遍历和后序遍历,求前序遍历
void binary_tree_preorder(char* inorder, char* postorder, int length){
	if (length == 0)
		return;
	char root = postorder[length-1];
	cout << root << " ";
	int index = 0;
	for (; index < length; index++){
		if (inorder[index] == root)
			break;
	}
	binary_tree_preorder(inorder, postorder, index);
	binary_tree_preorder(inorder + index + 1, postorder + index, length - index - 1);
}
int main(){
	char* preorder = "ABDHKECFIGJ";
	char* inorder = "HKDBEAIFCGJ";
	char* postorder = "KHDEBIFJGCA";

	binary_tree_postorder(preorder, inorder, 11);
	cout << endl;
	binary_tree_preorder(inorder, postorder, 11);
	cout << endl;

	return 0;
}

参考:

http://blog.youkuaiyun.com/feliciafay/article/details/6816871

http://blog.youkuaiyun.com/feliciafay/article/details/6817851

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值