題目描述
輸入某二叉樹的前序周遊和中序周遊的結果,請重建出該二叉樹。假設輸入的前序周遊和中序周遊的結果中都不含重複的數字。例如輸入前序周遊序列{1,2,4,7,3,5,6,8}和中序周遊序列{4,2,7,1,5,3,8,6},則重建二叉樹并傳回。
Solution
先序序列第一個數就是根結點而後是左子樹的先序序列和右子樹的先序序列,而中序序列是先是左子樹的中序序列,然後是根結點,最後是右子樹的中序序列。用根結點将中序分出左右子樹序列,繼而得到先序的左右子樹序列,遞歸重建。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root = reBuild(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
public TreeNode reBuild(int[] pre, int startP, int endP, int[] in, int startI, int endI) {
if (startP > endP || startI > endI) return null;
TreeNode root = new TreeNode(pre[startP]);
for (int i = startI; i <= endI; i++)
if (in[i] == pre[startP]) {
root.left = reBuild(pre, startP + 1, startP + i - startI, in, startI, i - 1);
root.right = reBuild(pre, startP + i - startI + 1, endP, in, i + 1, endI);
break;
}
return root;
}
}