題目:給定二叉樹的前序遍歷與中序遍歷結果,重建這棵二叉樹。
示例:
前序遍歷數組 preArr[] = {1, 2, 4, 5, 3, 6, 7}
中序遍歷數組 inArr[] = {4, 2, 5, 1, 6, 3, 7}
利用兩種遍歷的性質反推即可。前序遍歷的第一個元素必然是根節點,這裡是 1;再到中序遍歷中找到 1 的位置,它左側的 {4, 2, 5} 就是左子樹,右側的 {6, 3, 7} 就是右子樹。左子樹有 3 個節點,那麼前序數組中緊跟根節點的 3 個元素 {2, 4, 5} 就是左子樹的前序序列,剩下 {3, 6, 7} 是右子樹的前序序列。對左右子樹重複同一套推導,遞迴到底即可。
public class Solution {
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
TreeNode root = new TreeNode(pre[0]); // 前序的第一個數定為根
int len = pre.length;
// 只有一個數時即為葉節點
if (len == 1) {
root.left = null;
root.right = null;
return root;
}
// 在中序中找到根的位置
int rootval = root.val;
int i;
for (i = 0; i < len; i++) {
if (rootval == in[i])
break;
}
// 創建左子樹
if (i > 0) {
int[] pr = new int[i];
int[] ino = new int[i];
for (int j = 0; j < i; j++) {
pr[j] = pre[j + 1];
}
for (int j = 0; j < i; j++) {
ino[j] = in[j];
}
root.left = reConstructBinaryTree(pr, ino);
} else {
root.left = null;
}
// 創建右子樹
if (len - i - 1 > 0) {
int[] pr = new int[len - i - 1];
int[] ino = new int[len - i - 1];
for (int j = i + 1; j < len; j++) {
ino[j - i - 1] = in[j];
pr[j - i - 1] = pre[j];
}
root.right = reConstructBinaryTree(pr, ino);
} else {
root.right = null;
}
return root;
}
public static void main(String[] args) {
int[] preArr = {1, 2, 4, 5, 3, 6, 7};
int[] inArr = {4, 2, 5, 1, 6, 3, 7};
Solution s = new Solution();
TreeNode root = s.reConstructBinaryTree(preArr, inArr);
s.postOrder(root);
}
}
這份實現的優點是直觀,缺點是每層遞迴都在複製子數組,時間與空間開銷偏大。面試中更優的写法是只傳遞下標區間(preStart、preEnd、inStart、inEnd),配合一個 HashMap 記錄中序中每個值的位置,把查找根的 O(n) 降到 O(1),整體時間複雜度可壓到 O(n),且不再反覆分配數組。
值得補充的是,僅靠前序與後序無法唯一確定一棵二叉樹,必須「前序 + 中序」或「後序 + 中序」的組合才足夠,這也是本題成立的前提。