Cheating with binary tree goop

This commit is contained in:
Dan Buch 2023-10-24 15:42:42 -04:00
parent 10ec594031
commit ffb16efcdc
Signed by: meatballhat
GPG Key ID: A12F782281063434
3 changed files with 64 additions and 1 deletions

View File

@ -46,8 +46,8 @@ class TreeNode:
for key, value in [
("val", self.val),
("right", self.right),
("left", self.left),
("right", self.right),
]:
if value is not None:
filtered_parts.append((key, value))

View File

@ -319,3 +319,34 @@ def binary_tree_from_list(inlist: list[int | None]) -> stdlib.BinaryTreeNode | N
node.right = nodes_copy.pop()
return root
def binary_tree_from_preorder_inorder(
preorder: list[int], inorder: list[int]
) -> stdlib.BinaryTreeNode | None:
preorder_reversed = preorder[::-1]
def subtree(left: list[int], right: list[int]) -> stdlib.BinaryTreeNode:
root: stdlib.BinaryTreeNode = typing.cast(
stdlib.BinaryTreeNode, stdlib.TreeNode(preorder_reversed.pop())
)
if len(left) > 1:
split_pos = left.index(preorder_reversed[-1])
root.left = subtree(left[:split_pos], left[split_pos + 1 :])
elif len(left) == 1:
preorder_reversed.remove(left[0])
root.left = typing.cast(stdlib.BinaryTreeNode, stdlib.TreeNode(left[0]))
if len(right) > 1:
split_pos = right.index(preorder_reversed[-1])
root.right = subtree(right[:split_pos], right[split_pos + 1 :])
elif len(right) == 1:
preorder_reversed.remove(right[0])
root.right = typing.cast(stdlib.BinaryTreeNode, stdlib.TreeNode(right[0]))
return root
split_pos = inorder.index(preorder[0])
return subtree(inorder[:split_pos], inorder[split_pos + 1 :])

View File

@ -229,3 +229,35 @@ def test_binary_tree_from_list(
inlist: list[int | None], expected: stdlib.BinaryTreeNode | None
):
assert stuff.binary_tree_from_list(inlist) == expected
@pytest.mark.parametrize(
("preorder", "inorder", "expected"),
[
(
[3, 9, 20, 15, 7],
[9, 3, 15, 20, 7],
stdlib.TreeNode(
3,
left=stdlib.TreeNode(9),
right=stdlib.TreeNode(
20, left=stdlib.TreeNode(15), right=stdlib.TreeNode(7)
),
),
),
(
[-1],
[-1],
stdlib.TreeNode(-1),
),
(
[1, 2],
[1, 2],
stdlib.TreeNode(1, right=stdlib.TreeNode(2)),
),
],
)
def test_binary_tree_from_preorder_inorder(
preorder: list[int], inorder: list[int], expected: stdlib.BinaryTreeNode
):
assert stuff.binary_tree_from_preorder_inorder(preorder, inorder) == expected