1.已知一棵二叉树的先序遍历序列和中序遍历序列分别是abdgcef、dgbaecf,求二叉树的后序遍历序列 。
按照陈越姥姥的思路 https://www.bilibili.com/video/av18586085/?p=89
步骤:
通过前序和中序确定root和左子树、右子树,然后重建二叉树
1.确定根节点 a 树分为 左子树 bdg 和右子树 cef (根据中序遍历) a放在结果末尾
2.将bdg看出一棵树 根节点为 b ,左子树dg ,右子树为空 b 放入结果中
3.将dg看成一棵树 根节点为 d, dg 放入结果中
4.cef 看成一棵树 根节点 为 c c放入结果中
5.ef 由 中序遍历ecf知 e 为左节点 ef 放入结果中
java代码实现
public class Main {
public static void main(String[] args) {
int[] pre={1,2,3,4,5,6};
int[] in={3,2,4,1,6,5};
int[] post=new int[6];
int preL=0,inL=0,postL=0;
solve(pre,in,post,preL,inL,postL,6);
for (int i : post) {
System.out.print(i+" ");
}
}
private static void solve(int[] pre, int[] in, int[] post, int preL, int inL, int postL, int n) {
if (n==0) return;
if (n==1) {post[postL]=pre[preL]; return;}
int root=pre[preL];
post[postL+n-1]=root;
int i=0;
for (;i<n;i++){
if (in[inL+i]==root) break;
}
int L=i,R=n-L-1; //划分左右子树
solve(pre,in,post,preL+1,inL,postL,L); //递归处理左子树
solve(pre,in,post,preL+L+1,inL+L+1,postL+L,R); //递归处理右子树
}
}
通过后序和中序来得到前序,也是一样的实现