回顾一下二叉树的三种遍历
先序: 根->左->右
中序:左->根->右
后序:左->右->根
只要我们知道中序和先序或着后序 那么我们就可以根据已知的两种遍历序列
求出剩下的另一种遍历序列
例:已知该二叉树的先序遍历序列为:A-B-D-E-G-C-F,中序遍历序列为:D-B-G-E-A-C-F。求该二叉树后序遍历序列
第一步:找根 先序遍历先遍历根结点 那么它的序列第一个肯定是根节点也就是上面的A
第二步:找根结点的左右子数 中序遍历先左后根后右 在中序序列中找到根结点的位置那么它的左边就是它的左子树序列 右边就是它的右子数序列
即上面的 D-B-G-E 和 C-F
第三步:拆分转化为子问题 去掉A结点 将树分为两个二叉树 B-D-E-G 和C-F
然后按照第一步分别找两颗树的根 B C 然后根据第二部找根的左右子数
B(左边D 右边 G-E) C (左边NULL 右边 F) 一次类推 直到还原出二叉树的模型
最后我们就可以根据后续遍历规则得出该二叉树的后续遍历序列为:D-G-E-B-F-C-A。
package demo4.tcyll;
import java.util.HashMap;
import java.util.Scanner;
class TreeNode {
Character val;
TreeNode left;
TreeNode right;
TreeNode(Character x) { val = x; }
}
//ABCDEFGH,BDCEAFHG
public class Main1 {
static int pre_idx = 0;
static char [] preorder;
static char[] inorder;
static HashMap<Character, Integer> idx_map = new HashMap<Character,
Integer>();
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] split = line.split(",");
preorder = split[0].toCharArray();
inorder = split[1].toCharArray();
int idx = 0;
for (Character val : inorder)
idx_map.put(val, idx++);
TreeNode head = helper(0, inorder.length);
sort(head);
System.out.println(sb.toString());
}
public static void sort(TreeNode head){
if(head == null){
return ;
}
sort(head.left);
sort(head.right);
sb.append(head.val);
}
public static TreeNode helper(int in_left, int in_right) {
if (in_left == in_right)
return null;
Character root_val = preorder[pre_idx];
TreeNode root = new TreeNode(root_val);
int index = idx_map.get(root_val);
pre_idx++;
root.left = helper(in_left, index);
root.right = helper(index + 1, in_right);
return root;
}
}