我们经常会遇到这种问题:已知二叉树先序、中序、后序遍历中的两种,求另外一种排序。一般做这种题都是画出二叉树然后写出另一种遍历,今天系统地研究了一下,发现其实我们也可以用编程的方法来完成。
若已知先序、中序遍历,求后序遍历以及已知中序、后序遍历,求先序遍历是可以实现的,而已知先序、后序遍历,求中序遍历无法完成,因为这种情况下若一个结点只有一条边,此时不知道这条边到底是左子树还是右子树。
已知先序、中序遍历,求后序遍历
可以用递归来实现,步骤为:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
我们用这种方式来输出这棵树:
代码为:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct TreeNode{
struct TreeNode* left;
struct TreeNode* right;
char data;
};
void BinaryTreeFromOrderings(char* inorder, char* preorder, int length){
int rootIndex=0;
if(length==0){
return;
}
TreeNode* node = new TreeNode;
node->data=*preorder;
for(;rootIndex<length;rootIndex++){
if(inorder[rootIndex]==*preorder){
break;
}
}
//Left
BinaryTreeFromOrderings(inorder, preorder+1,rootIndex);
//Right
BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
cout<<node->data<<endl;
return;
}
int main(){
char* pr="GDAFEMHZ";
char* in="ADEFGHMZ";
BinaryTreeFromOrderings(in,pr,8);
printf("\n");
return 0;
}
输出结果:
经检验,该结果为正确的。
已知中序、后序遍历,求先序遍历
求解过程依然使用递归且思路与上面类似:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
依然使用输出上面那颗树。
代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct TreeNode{
struct TreeNode* left;
struct TreeNode* right;
char data;
};
TreeNode* BinaryTreeFromOrderings(char* inorder,char* aftorder,int length){
if(length == 0){
return NULL;
}
TreeNode* node= new TreeNode;
node->data=*(aftorder+length-1);
cout<<node->data<<endl;
int rootIndex=0;
for(;rootIndex<length;rootIndex++){
if(inorder[rootIndex]==*(aftorder+length-1))
break;
}
node->left=BinaryTreeFromOrderings(inorder,aftorder,rootIndex);
node->right=BinaryTreeFromOrderings(inorder+rootIndex+1,aftorder+rootIndex,length-(rootIndex+1));
return node;
}
int main(){
char* af="AEFDHZMG";
char* in="ADEFGHMZ";
BinaryTreeFromOrderings(in,af,8);
printf("\n");
return 0;
}
输出结果为:
经检验,该结果也是正确的。