From 7a277c6ccc61548a15c440530f5b938f8378500e Mon Sep 17 00:00:00 2001 From: Pavel Karateev Date: Mon, 4 Nov 2024 21:56:38 +0100 Subject: [PATCH] solve "106. Construct Binary Tree from Inorder and Postorder Traversal" --- ...ee_from_inorder_and_postorder_traversal.py | 32 +++++++++++++++++++ ...ee_from_inorder_and_postorder_traversal.py | 18 +++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/construct_binary_tree_from_inorder_and_postorder_traversal.py create mode 100644 tests/test_construct_binary_tree_from_inorder_and_postorder_traversal.py diff --git a/src/construct_binary_tree_from_inorder_and_postorder_traversal.py b/src/construct_binary_tree_from_inorder_and_postorder_traversal.py new file mode 100644 index 0000000..70f279a --- /dev/null +++ b/src/construct_binary_tree_from_inorder_and_postorder_traversal.py @@ -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) diff --git a/tests/test_construct_binary_tree_from_inorder_and_postorder_traversal.py b/tests/test_construct_binary_tree_from_inorder_and_postorder_traversal.py new file mode 100644 index 0000000..0353806 --- /dev/null +++ b/tests/test_construct_binary_tree_from_inorder_and_postorder_traversal.py @@ -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