題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
思路
我們知道,前序遍歷的第一個節點就是樹的根節點,所以我們先根據前序遍歷序列的第一個數字創建根結點,接下來在中序遍歷序列中找到根結點的位置,根節點的左邊就是左子樹,右邊就是右子樹,這樣就能確定左、右子樹結點的數量。在前序遍歷和中序遍歷的序列中劃分了左、右子樹結點的值之後,就可以遞歸地去分別構建它的左右子樹。
參考代碼
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
// 終止條件
if (pre == null || pre.length == 0) {
return null;
}
// 創建根節點
TreeNode root = new TreeNode(pre[0]);
// 獲取到根節點在中序數組的索引
int index = findIndex(pre, in);
// 前序數組左子樹的索引爲[1, index + 1), 中序數組左子樹的索引爲[0, index)
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, index + 1), Arrays.copyOfRange(in, 0, index));
// 前序數組右子樹的索引爲[index + 1, pre.length), 中序數組右子樹的索引爲[index + 1, in.length)
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, index + 1, pre.length), Arrays.copyOfRange(in, index + 1, pre.length));
return root;
}
private int findIndex(int [] pre, int [] in) {
for (int i = 0; i < in.length; i++) {
if (in[i] == pre[0]) {
return i;
}
}
return -1;
}
}