mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update and rename bt_construction_inorder_postorder.py to bt_construct_inorder_postorder.py
This commit is contained in:
parent
dd98393aa4
commit
b61c58b158
25
trees/bt_construct_inorder_postorder.py
Normal file
25
trees/bt_construct_inorder_postorder.py
Normal file
@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
|
||||
def build_tree(left, right, index_map):
|
||||
|
||||
if left > right:
|
||||
return None
|
||||
|
||||
root = Node(postorder.pop()) # this order change from preorder
|
||||
index_here = index_map[root.val]
|
||||
|
||||
root.right = build_tree(index_here + 1, right, index_map) # this order change from preorder
|
||||
root.left = build_tree(left, index_here - 1, index_map)
|
||||
|
||||
return root
|
||||
|
||||
|
||||
def build_tree(inorder, postorder) -> Optional[Node]:
|
||||
|
||||
index_map = {val: i for i, value in enumerate(inorder)}
|
||||
|
||||
return fill_tree(0, len(inorder) - 1, index_map)
|
||||
|
@ -1,29 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
# 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 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
|
||||
|
||||
|
||||
def build_tree(inorder: list[int], postorder: list[int]) -> Optional[TreeNode]:
|
||||
|
||||
inorder_map = {val: index for index, val in enumerate(inorder)}
|
||||
return fill_tree(0, len(inorder) - 1, inorder_map)
|
||||
|
Loading…
x
Reference in New Issue
Block a user