重建二叉樹
1.題目描述
輸入某二叉樹的前序周遊和中序周遊的結果,請重建出該二叉樹。假設輸入的前序周遊和中序周遊的結果中都不含重複的數字。例如輸入前序周遊序列{1,2,4,7,3,5,6,8}和中序周遊序列{4,7,2,1,5,3,8,6},則重建二叉樹并傳回。
2.題目示例
3.思路及代碼
- 思路:遞歸
- 根據前序找到根節點
- 根據根節點在中序中找到左右子樹
- 依此遞歸即可
- 代碼:
/**
* 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) {
if(pre.length == 0 || in.length == 0 || pre.length != in.length){
return null;
}
return reConstructBinaryTreeHelper(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
public TreeNode reConstructBinaryTreeHelper(int [] pre,int pre_start, int pre_end, int [] in, int in_start, int in_end) {
//遞歸退出條件
if(pre_start > pre_end || in_start > in_end){
return null;
}
TreeNode root = new TreeNode(pre[pre_start]);
for(int i = in_start; i <= in_end; i++){
if(in[i] == pre[pre_start]){
root.left = reConstructBinaryTreeHelper(pre, pre_start + 1, i - in_start + pre_start, in, in_start, i - 1);
root.right = reConstructBinaryTreeHelper(pre, i - in_start + pre_start + 1, pre_end, in, i + 1, in_end);
break;
}
}
return root;
}
}