Problem · Tree
Minimum-Sum Root-to-Leaf Path
Learn this problemProblem statement
Given the root of a nonempty binary tree whose nodes contain signed integers, return the values along a root-to-leaf path whose node-value sum is minimum.
A leaf has no left or right child. If several root-to-leaf paths have the same minimum sum, return the first one encountered by a depth-first traversal that explores each node's left child before its right child.
Return the selected path as an integer array ordered from the root to the leaf.
Function
minimumSumRootToLeafPath(root: TreeNode) → int[]Examples
Example 1
root = [1,2,3,4,5,6,7]return = [1,2,4]The four root-to-leaf sums are 7, 8, 10, and 11. The minimum is 1 + 2 + 4 = 7.
Example 2
root = [5,1,1]return = [5,1]Both leaves produce a sum of 6. The left leaf is visited first, so the left path is returned.
Example 3
root = [10,-5,2,null,-10]return = [10,-5,-10]The left path has sum -5, while the right path has sum 12. Negative values therefore make the deeper left path optimal.
Constraints
- The tree contains between
1and100000nodes. -1000000000 <= node.val <= 1000000000.- Every root-to-leaf sum fits in a signed 64-bit integer.
- The input is a valid finite binary tree encoded in level order with explicit
nullchildren.