def util(start: int, end: int) -> TreeNode:
            if end < start:
                return None

            mid = (start + end) // 2
            root = TreeNode(array[mid])
            root.left = util(start, mid - 1)
            root.right = util(mid + 1, end)
            return root
        def util(left, right) -> TreeNode:
            if left > right:
                return None

            value = preorder.pop(0)
            head = TreeNode(value)

            head.left = util(left, inorder_value_index_map[value] - 1)
            head.right = util(inorder_value_index_map[value] + 1, right)

            return head
    def run():
        tree = TreeNode(1)
        tree.left = TreeNode(2)
        tree.left.left = TreeNode(4)
        tree.left.right = TreeNode(5)
        tree.left.left.left = TreeNode(7)
        tree.right = TreeNode(3)
        tree.right.right = TreeNode(6)
        tree.right.right.right = TreeNode(8)

        print_tree(tree)

        assert Solution().deepestLeavesSum(tree) == 15
Example #4
0
        def dfs(node: TreeNode, parent: TreeNode, is_right):
            if not node:
                return

            if node.value in to_delete:
                if parent:
                    if is_right:
                        parent.right = None
                    else:
                        parent.left = None

                if node.left and node.left.value not in to_delete:
                    res.append(node.left)
                if node.right and node.right.value not in to_delete:
                    res.append(node.right)

            dfs(node.left, node, False)
            dfs(node.right, node, True)
Example #5
0
            this_level.append(root)

        while len(this_level):
            next_level = []

            # To make left side view, we just need to take this_level[0] instead
            res.append(this_level[-1].value)

            for n in this_level:
                if n.left:
                    next_level.append(n.left)
                if n.right:
                    next_level.append(n.right)

            this_level = next_level

        return res


tree = TreeNode(1)
tree.left = TreeNode(2)
tree.left.left = TreeNode(5)
tree.right = TreeNode(3)
# tree.right.right = TreeNode(4)
# tree.right.left = TreeNode(6)

print_tree(tree)

s = Solution()
print(s.rightSideView(tree))