Two Subtrees Apart
You are given the root of a binary tree whose values may be negative. A subtree is a node together with everything below it, and it is worth the sum of its values.
Pick two subtrees that share no node, which means that neither of the two picked nodes lies below the other. Return the largest total worth of two such subtrees.
At least one node of the tree has two children, so a pick always exists.
Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.
Example 1
The subtree at 4 is worth 4 + 1 + 2 = 7, and the leaf 6 is worth 6.
Example 2
The leaves 8 and 9 beat any pick that takes the -10 along.
Example 3
Two subtrees have to be picked, even when both are losses.
Constraints
3 <= number of nodes <= 40, and some node has two children-1000 <= node.val <= 1000
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Trees problems
- Two Swapped ValuesHard
- Binary Tree Inorder TraversalBeginner
- Binary Tree Postorder TraversalBeginner
- Binary Tree Preorder TraversalBeginner
- Collect the LeavesBeginner
- Count the LeavesBeginner
- Full Binary Tree CheckBeginner
- Is It a Single ChainBeginner