Instructions
You are given the root of a binary tree. Every node holds a whole number, and the numbers can be negative.
A path is a sequence of nodes where each pair of neighbours in the sequence is joined by an edge of the tree. A path:
- has at least one node;
- uses each node at most once;
- does not need to pass through the root, and does not need to start or end at a leaf.
The sum of a path is the total of the values of its nodes. Return the largest path sum in the tree.
How the input is shown
The tree is written in level order: the values row by row, from left to right, with null where a child is missing. For example, [1, 2, 3, null, 4] is the root 1 with children 2 and 3, and 4 is the right child of 2. Your function gets the TreeNode root, with fields val, left and right.
Hint
For each node, find the best sum of a path that starts at this node and goes down into one side only. A child whose best is below zero helps nobody, so treat it as zero. The best path that bends at this node is its value plus the best of the left side plus the best of the right side.
Examples
Example 1
- Input:
- [4,-7,9,2,null,-3,6]
- Output:
- 19
The path 4 -> 9 -> 6 has the sum 19. Going left from 4 only adds -7 + 2 = -5, and adding -3 under 9 also makes the sum smaller.
Example 2
- Input:
- [-5,8,3,-2,7]
- Output:
- 15
The best path is 8 -> 7 with the sum 15. It does not use the root: going up to -5 and down to 3 gives 7 + 8 - 5 + 3 = 13, which is smaller.
Example 3
- Input:
- [-6,-9,-4]
- Output:
- -4
Every value is negative, so the best path is the single node -4. A path must have at least one node, so the answer cannot be 0.
Constraints
- The tree has between
1and40nodes. -50 <= Node.val <= 50
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [4,-7,9,2,null,-3,6]
- Expected:
- 19
- Input:
- [-5,8,3,-2,7]
- Expected:
- 15
- Input:
- [-6,-9,-4]
- Expected:
- -4
Run checks your code against the 3 examples. Submit checks it against all 163 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.