Skip to content

Commit

Permalink
solve "106. Construct Binary Tree from Inorder and Postorder Traversal"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Nov 4, 2024
1 parent 544167d commit 7a277c6
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/construct_binary_tree_from_inorder_and_postorder_traversal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from src.utils.binary_tree import TreeNode


class Solution:
def buildTree(
self, inorder: list[int], postorder: list[int]
) -> TreeNode | None:
n = len(inorder)
postorder_idx = n - 1

def dfs(left: int, right: int) -> TreeNode | None:
nonlocal postorder_idx

if left > right:
return None

value = postorder[postorder_idx]
inorder_idx = val_to_inorder_idx[value]
node = TreeNode(value)

postorder_idx -= 1

node.right = dfs(inorder_idx + 1, right)
node.left = dfs(left, inorder_idx - 1)

return node

val_to_inorder_idx: dict[int, int] = {}
for idx, val in enumerate(inorder):
val_to_inorder_idx[val] = idx

return dfs(0, n - 1)
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import pytest

from src.construct_binary_tree_from_inorder_and_postorder_traversal import (
Solution,
)
from src.utils.binary_tree import tree_to_list


@pytest.mark.parametrize(
"inorder,postorder,expected_out_list",
(
([9, 3, 15, 20, 7], [9, 15, 7, 20, 3], [3, 9, 20, None, None, 15, 7]),
([-1], [-1], [-1]),
),
)
def test_solution(inorder, postorder, expected_out_list):
out_tree = Solution().buildTree(inorder, postorder)
assert tree_to_list(out_tree) == expected_out_list

0 comments on commit 7a277c6

Please sign in to comment.