-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solve "106. Construct Binary Tree from Inorder and Postorder Traversal"
- Loading branch information
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
32 changes: 32 additions & 0 deletions
32
src/construct_binary_tree_from_inorder_and_postorder_traversal.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
18 changes: 18 additions & 0 deletions
18
tests/test_construct_binary_tree_from_inorder_and_postorder_traversal.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |