From ffb16efcdc7244d69372e3ec48f87a9e1afab4e3 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Tue, 24 Oct 2023 15:42:42 -0400 Subject: [PATCH] Cheating with binary tree goop --- leetcode/stdlib.py | 2 +- leetcode/stuff.py | 31 +++++++++++++++++++++++++++++++ leetcode/test_stuff.py | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/leetcode/stdlib.py b/leetcode/stdlib.py index e307202..20f67f1 100644 --- a/leetcode/stdlib.py +++ b/leetcode/stdlib.py @@ -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)) diff --git a/leetcode/stuff.py b/leetcode/stuff.py index ff5b1f9..8c1f04d 100644 --- a/leetcode/stuff.py +++ b/leetcode/stuff.py @@ -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 :]) diff --git a/leetcode/test_stuff.py b/leetcode/test_stuff.py index 042d5b1..8d48ae7 100644 --- a/leetcode/test_stuff.py +++ b/leetcode/test_stuff.py @@ -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