PAT 1036 Boys vs Girls
阿新 • • 發佈:2021-01-24
技術標籤:java演算法
題目 劍指 Offer 07. 重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。
例如,給出
前序遍歷 preorder = [3,9,20,15,7]
中序遍歷 inorder = [9,3,15,20,7]
返回如下的二叉樹:
3
/
9 20
/
15 7
限制:
0 <= 節點個數 <= 5000
注意:本題與主站 105 題重複:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
思路
先序確定根,中序分左右
複雜度分析
時間:O(n)
空間: O(n)
程式碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0) {
return null;
}
for(int i = 0; i < inorder.length; ++i) {
map.put(inorder[i], i);
}
return buildTree(0, preorder, 0, inorder.length - 1);
}
// 中序遞迴確定左右子樹節點樹數量, 先序確定根節點並由其左右節點數量確定左右子樹區間
TreeNode buildTree(int preIndex, int[] preorder, int instart, int inend) {
if(instart > inend) { return null;}
TreeNode root = new TreeNode(preorder[preIndex]);
int pos = map.get(preorder[preIndex]);
root.left = buildTree(preIndex + 1, preorder, instart, pos - 1);
root.right = buildTree(preIndex + pos - instart + 1, preorder, pos + 1, inend);
return root;
}
}