mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-07-14 10:39:47 -04:00
Create construct_tree.py
This commit is contained in:
parent
5ec8587911
commit
135c6bd58a
1 changed files with 25 additions and 0 deletions
25
trees_and_graphs/construct_tree.py
Normal file
25
trees_and_graphs/construct_tree.py
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
# Given two integer arrays inorder and postorder where inorder is the inorder
|
||||||
|
# traversal of a binary tree and postorder is the postorder traversal of the
|
||||||
|
# same tree, construct and return the binary tree.
|
||||||
|
|
||||||
|
def build_tree(inorder: list[int], postorder: list[int]) -> Optional[TreeNode]:
|
||||||
|
|
||||||
|
def fill_tree(i_left, i_right, inorder_map):
|
||||||
|
|
||||||
|
if i_left > i_right:
|
||||||
|
return None
|
||||||
|
|
||||||
|
val = postorder.pop()
|
||||||
|
root = TreeNode(val)
|
||||||
|
|
||||||
|
index_here = inorder_map[val]
|
||||||
|
|
||||||
|
root.right = fill_tree(index_here + 1, i_right, inorder_map)
|
||||||
|
root.left = fill_tree(i_left, index_here - 1, inorder_map)
|
||||||
|
|
||||||
|
return root
|
||||||
|
|
||||||
|
inorder_map = {val: index for index, val in enumerate(inorder)}
|
||||||
|
|
||||||
|
return fill_tree(0, len(inorder) - 1, inorder_map)
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue