mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update bt_construct_inorder_preorder.py
This commit is contained in:
parent
83fc152596
commit
e5efd5424a
@ -2,24 +2,24 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# author: bt3gl
|
# author: bt3gl
|
||||||
|
|
||||||
def build_tree(preorder: list[int], inorder: list[int]) -> Optional[Node]:
|
|
||||||
|
|
||||||
def helper(i_left, i_right, index_map):
|
def build_tree(preorder, inorder) -> Optional[Node]:
|
||||||
|
|
||||||
if i_left > i_right:
|
def helper(left, right, index_map):
|
||||||
|
|
||||||
|
if left > right:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
root = TreeNode(preorder.pop(0))
|
root = Node(preorder.pop(0))
|
||||||
index_here = index_map[root.val]
|
index_here = index_map[root.val]
|
||||||
|
|
||||||
# this order change from postorder
|
# this order change from postorder
|
||||||
root.left = helper(i_left, index_here - 1, index_map)
|
root.left = helper(left, index_here - 1, index_map)
|
||||||
root.right = helper(index_here + 1, i_right, index_map)
|
root.right = helper(index_here + 1, right, index_map)
|
||||||
|
|
||||||
return root
|
return root
|
||||||
|
|
||||||
|
index_map = {value: i for i, value in enumerate(inorder)}
|
||||||
index_map = {value: index for index, value in enumerate(inorder)}
|
|
||||||
|
|
||||||
return helper(0, len(inorder) - 1, index_map)
|
return helper(0, len(inorder) - 1, index_map)
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user