Ctrl K

Cutting Weak Branches

Medium
You are given the root of a binary tree and an integer threshold. A path sum is the total of the node values along a path from the root down to a leaf (a node with no children). A node is weak if **every** root-to-leaf path passing through it has a sum strictly below threshold. Remove all weak nodes at once (together with their subtrees) and return the root of the resulting tree. If the root itself is removed, return an empty tree.
Example 1
root=tree_node([4, 9, -2, None, None, 1, -6]), threshold=5 → [4, 9]

The root-to-leaf sums are 4+9 = 13, 4-2+1 = 3 and 4-2-6 = -4. Leaves 1 and -6 lie only on weak paths and are removed; node -2 loses both children since every path through it is weak, so it goes too.

Example 2
root=tree_node([3, -1, 5, 8, -7]), threshold=10 → [3, -1, None, 8]

The sums are 3-1+8 = 10, 3-1-7 = -5 and 3+5 = 8. Only the path 3 → -1 → 8 survives.

Example 3
root=tree_node([2, 1]), threshold=4 → None

The only path sums to 3 < 4, so the whole tree is removed.

Constraints
  • 1 ≤ number of nodes ≤ 5000
  • -10⁵ ≤ Node.val ≤ 10⁵
  • -10⁹ ≤ threshold ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([4, 9, -2, None, None, 1, -6]), threshold=5
Expected
[4, 9]

Run checks the first 3 tests in your browser. Submit checks all 63 tests on the server, hidden ones included.