progress

~/problems / Trees / Binary trees

Orchard: branches that need a prop

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

An orchard keeper models an apple tree as a binary tree; node.val is the apples hanging at that branch point. A point's load is its own apples plus every apple below it. A load strictly more than limit needs a wooden prop.

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

Write props_needed(root, limit) -> list[int]: the loads that need a prop, in postorder (left subtree, right subtree, node). An empty tree needs none.

#         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)   # []

Up to 5,000 nodes, apples 0 to 100 per node.

⭐ Bonus: a speed test on a 5,000-node chain earns a star if you compute each load once (O(n)) and handle the depth (sys.setrecursionlimit or a stack).

Show hint

a helper load(node) = node.val + load(node.left) + load(node.right); recording each load just 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