給定二叉樹的中序遍歷序列 Inorder 與後序遍歷序列 Postorder(節點用大寫字母表示,長度 ≤ 8),求前序遍歷序列 Preorder。
範例:
Inorder: B A D C
Postorder: B D C A
Preorder: A B C D
root = post[post_len-1],輸出(前序首)。root 下標 idx。idx,右子樹規模 = in_len - idx - 1。in[0..idx-1], post[0..idx-1]in[idx+1..end], post[idx..post_len-2]import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String in = sc.nextLine().trim();
String post = sc.nextLine().trim();
showResult(in, post);
System.out.println();
}
}
static void showResult(String in, String post) {
if (in.isEmpty()) return;
char root = post.charAt(post.length() - 1);
System.out.print(root);
int idx = in.indexOf(root);
if (idx > 0)
showResult(in.substring(0, idx), post.substring(0, idx));
if (idx < in.length() - 1)
showResult(in.substring(idx + 1), post.substring(idx, post.length() - 1));
}
}
indexOf 掃描 O(n),共 n 層。in.isEmpty() 直接返回。idx(跳過左子樹 idx 個元素),結尾排除根節點。同理遞歸,返回 TreeNode 而非直接打印。LeetCode 106「從中序與後序遍歷構造二叉樹」即為此變體。