FunctionRacerProblemsRace

Two Subtrees Apart

HardTreesPython, JavaScript, TypeScript, Java, C++

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

root [5,4,6,1,2]
returns 13

The subtree at 4 is worth 4 + 1 + 2 = 7, and the leaf 6 is worth 6.

Example 2

root [1,-10,5,8,9]
returns 17

The leaves 8 and 9 beat any pick that takes the -10 along.

Example 3

root [1,-2,-3]
returns -5

Two subtrees have to be picked, even when both are losses.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems