1. 程式人生 > >【樹】已知二叉樹前序和中序遍歷求後序遍歷,及中序和後序遍歷求前序遍歷

【樹】已知二叉樹前序和中序遍歷求後序遍歷,及中序和後序遍歷求前序遍歷

#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;
}

參考: