#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
本文详细介绍了如何通过已知的二叉树中序遍历和后序遍历序列,推导出其前序遍历序列的方法。包括具体的算法实现和实例演示,旨在帮助读者理解和掌握二叉树遍历的相关概念。
2368

被折叠的 条评论
为什么被折叠?



