Rename construct_tree_inorder_postorder.py to bt_construction_inorder_postorder.py

This commit is contained in:
marina 2023-08-03 13:14:17 -07:00 committed by GitHub
parent 1a9f793b21
commit 753ce86ad2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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)