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

#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.csdn.net/feliciafay/article/details/6816871

http://blog.csdn.net/feliciafay/article/details/6817851

你可能感兴趣的:(【树】已知二叉树前序和中序遍历求后序遍历,及中序和后序遍历求前序遍历)