利用二叉树中序及后序遍历确定该二叉树的先序序列
中序遍历:DCBFEGAH
后序遍历:DCFGEBHA
根据中序遍历和后续遍历的性质:
1.它们都是先遍历左子树。
2.后序遍历中从右到左依次为对应子树的根结点。
3.中序遍历中若我们找到一个根节点,那么在一个范围内,根节点的左边为左子树,右边为右子树。
过程如下:
1.DCBFEG AH
DCFGEB HA, A为根节点,在中序遍历中它的左边即为左子树(6个节点),右边为右子树(1个节点);在后序遍历中我们即可根据左右子树的节点个数确定后序遍历中的左右子树,根据后序遍历的性质,我们即可确定左右子树的根节点分别为:B,H。
接下来就是根据左右子树的根节点再进行如上的过程
2.
DC BFEG
DC FGEB
3.
…
重要的就是 选取好分段点
这里还有:利用二叉树中序及先序遍历确定该二叉树的后序序列问题
代码1如下(通过数组):
#include"bits/stdc++.h"
using namespace std;
#define MAX 24
void preorder(char in[],char post[],int root,int start,int end){//root为根节点
if(start>end){
return;
}
char rot=post[root];
int index;
for(int i=0;i<strlen(in);i++){ //找到中序遍历中根节点所在位置
if(rot==in[i]){
index=i; //记录位置
break;
}
}
cout<<rot;
// getchar();
preorder(in,post,root-end+index-1,start,index-1); //左子树
preorder(in,post,root-1,index+1,end); //右子树
}
int main(){
char inorder[MAX],postorder[MAX];
cin>>inorder>>postorder;
preorder(inorder,postorder,strlen(inorder)-1,0,strlen(inorder)-1);
return 0;
}
/*
in:
DCBFEGAH
DCFGEBHA
out:
ABDFCEG
*/
代码2如下(通过string类):代码2参考于此
#include"bits/stdc++.h"
using namespace std;
void preorder(string inorder,string postorder){
if(!inorder.size()){
return;
}
char root;
int k;
root=postorder[postorder.length()-1];//后序遍历的末尾即为根节点
k=inorder.find(root);//找到root的索引
cout<<root;
preorder(inorder.substr(0,k),postorder.substr(0,k)); //左子树
preorder(inorder.substr(k+1),postorder.substr(k,inorder.length()-k-1)); //右子树
}
int main(){
string inorder,postorder;
cin>>inorder>>postorder;
preorder(inorder,postorder);
return 0;
}
//都是一个原理
/*这里对string.substr()说明一下:
若括号中为(0,5)则从索引为0的元素开始截取5位即(0,1,2,3,4),
若括号中为(5)则从索引为5的元素开始截取到末尾。
*/
/*
in:
DCBFEGAH
DCFGEBHA
out:
ABDFCEG
*/
若有错误,请指正