mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 04:36:08 -04:00
Create construct_tree_inorder_preorder.py
This commit is contained in:
parent
cf4a797646
commit
bfeb0bf97c
21
trees_and_graphs/construct_tree_inorder_preorder.py
Normal file
21
trees_and_graphs/construct_tree_inorder_preorder.py
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
def build_tree(preorder: list[int], inorder: list[int]) -> Optional[TreeNode]:
|
||||||
|
|
||||||
|
def helper(i_left, i_right, index_map):
|
||||||
|
|
||||||
|
if i_left > i_right:
|
||||||
|
return None
|
||||||
|
|
||||||
|
root = TreeNode(preorder.pop(0))
|
||||||
|
index_here = index_map[root.val]
|
||||||
|
|
||||||
|
# this order change from postorder
|
||||||
|
root.left = helper(i_left, index_here - 1, index_map)
|
||||||
|
root.right = helper(index_here + 1, i_right, index_map)
|
||||||
|
|
||||||
|
return root
|
||||||
|
|
||||||
|
|
||||||
|
index_map = {value: index for index, value in enumerate(inorder)}
|
||||||
|
|
||||||
|
return helper(0, len(inorder) - 1, index_map)
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user