題目描述:
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
代碼:
//Definition for binary tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root = reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
private TreeNode reConstructBinaryTree(int[] pre,int startPre,int endPre,int[] in,int startIn,int endIn){
//若是尾大於頭則退出程序
if(startPre > endPre || startIn > endIn)
return null;
//因爲前序二叉樹開頭第一個就是根節點
TreeNode root = new TreeNode(pre[startPre]);
for(int i = startIn; i <= endIn; i++){
if(pre[startPre] == in[i]){
//在中序中找到根節點,那麼左側的就是根結點的左子樹,右側的就是根節點的右子樹
//in 中序 。。。1 。。。。
//pre 前序 1 。。。。。。。
root.left = reConstructBinaryTree(pre, startPre + 1, startPre + (i - startIn), in, startIn, i - 1);
root.right = reConstructBinaryTree(pre, startPre + i - startIn + 1, endPre, in, i + 1, endIn);
}
}
return root;
}
提示:代碼中 i - startIn代表着左子樹節點的個數。