~/problems / Trees / Binary trees

Orchard: branches that need a prop

easy ~15 min

An orchard keeper models a young apple tree as a binary tree: every node is a branch point, node.val is the number of apples hanging right at that point, and its left and right children are the branches growing out of it. A branch point has to carry every apple at or above it: its own apples plus all the apples anywhere in its two subtrees. Any branch point whose load is strictly more than limit apples needs a wooden prop before harvest.

TreeNode(val, left=None, right=None) is in the starter. Keep it.

Write props_needed(root, limit) -> list[int]: the loads of the branch points that need a prop, in postorder (left subtree, right subtree, then the node), which is the order the keeper walks the tree. An empty tree (None) needs no props.

#         2              loads:      18
#        / \                       /    \
#       5   1                    12      4
#      / \   \                  /  \      \
#     4   3   3                4    3      3
props_needed(root, 3)    # [4, 12, 4, 18]
props_needed(root, 12)   # [18]
props_needed(root, 20)   # []

Constraints: up to 5000 nodes, apple counts are between 0 and 100, 0 <= limit. Trees can be lopsided, so plain recursion might go 5000 deep: either raise the recursion limit (sys.setrecursionlimit(10_000)) or walk the tree with a stack. Recomputing each node's load from scratch is O(n²) on a lopsided tree; compute every load once.

Show hint

make a helper that returns the load of a subtree: load(node) = node.val + load(node.left) + load(node.right). Because a node's load is known only after both children's, recording it right before returning gives postorder for free.

Topic: Binary trees. Recursive return values (height, best path), BFS by level, BST invariants.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc