题目描述
给定一个二叉树的前序遍历和中序遍历的序列,输出对应这个二叉树的后续遍历序列。
输入描述
输入为一行。 两个字符串,分别表示二叉树的前序遍历和中序遍历结果,用空格分隔,保证数据合法。
输出描述
对应输出后序遍历序列
示例
输入
ABDEC DBEAC
输出
DEBCA
题目解析
我们可以先通过先序序列和中序序列来构建出整个二叉树,然后再对整个二叉树进行后序遍历。
代码
import java.util.*;
class TreeNode{
char val;
TreeNode left;
TreeNode right;
TreeNode(char val){
this.val = val;
}
}
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
char[] pre = sc.next().toCharArray();
char[] in = sc.next().toCharArray();
TreeNode root = building(pre,in);
after(root);
}
public static TreeNode building(char[] pre,char[] in){
if(pre.length==0||in.length==0)
return null;
TreeNode root = new TreeNode(pre[0]);
for(int i =0;i<in.length;i++){
if(in[i]==pre[0]){
root.left=building(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));
root.right=building(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length));
}
}
return root;
}
public static void after(TreeNode root){
if(root == null)
return;
after(root.left);
after(root.right);
System.out.print(root.val);
}
}