class Solution {
HashMap<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
for(int i = 0; i < inorder.length; i++) map.put(inorder[i], i);
return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
TreeNode buildTree(int[] preorder, int pre_l, int pre_r, int[] inorder, int in_l, int in_r){
if(pre_l > pre_r || in_l > in_r) return null;
TreeNode root = new TreeNode(preorder[pre_l]);
int root_ind = map.get(preorder[pre_l]), left_size = root_ind - in_l;
root.left = buildTree(preorder, pre_l + 1, pre_l + left_size, inorder, in_l, root_ind - 1);
root.right = buildTree(preorder, pre_l + left_size + 1, pre_r, inorder, root_ind + 1, in_r);
return root;
}
}
剑指 Offer 07. 重建二叉树
最新推荐文章于 2024-08-14 20:03:33 发布