return if root.right and root.left: traverse_to_next(root.left).right = root.right if root.left: root.right = root.left root.left = None if root.right: self.flatten(root.right) def traverse_to_next(root: TreeNode) -> None: while True: while root.right: root = root.right if root.left: root = root.left else: return root root = TreeNode.from_array([1, 2, 5, 3, 4, Empty, 6]) expected = TreeNode(1) current = expected for i in range(2, 7): current.right = TreeNode(i) current = current.right Solution().flatten(root) assert TreeNode.subtrees_match(root, expected)
return root.max_seen # rob the root choice_1_value = root.val if root.left and root.left.left: choice_1_value += self.rob(root.left.left) if root.left and root.left.right: choice_1_value += self.rob(root.left.right) if root.right and root.right.left: choice_1_value += self.rob(root.right.left) if root.right and root.right.right: choice_1_value += self.rob(root.right.right) # don't rob the root choice_2_value = 0 if root.left: choice_2_value += self.rob(root.left) if root.right: choice_2_value += self.rob(root.right) maximum = max(choice_1_value, choice_2_value) root.max_seen = maximum return root.max_seen tree = TreeNode.from_array([3, 2, 3, TreeNode.EMPTY, 3, TreeNode.EMPTY, 1]) print(Solution().rob(tree)) tree2 = TreeNode.from_array([3, 4, 5, 1, 3, TreeNode.EMPTY, 1]) print(Solution().rob(tree2))