Loading...
You are given the root of a binary tree whose nodes hold integer keys.
A subtree is one node of the tree together with all of its descendants. A subtree is a binary search tree when all three of these hold:
A single node is always a binary search tree.
Return the largest key sum over all subtrees that are binary search trees. The empty subtree counts as well, and its key sum is 0, so the answer is never negative.
Your function receives root as a TreeNode. The node type is provided for you, with val, left, and right fields.
The examples below write the tree as its level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how the input is displayed; the decoding is done for you.
Node.val ≤4×104The subtree rooted at the key 3 holds 3, 2, 5, 4 and 6, and it is a binary search tree, so its key sum 20 counts. The whole tree is not one, because the left child of the root holds 4 with a child holding 4 again.
The subtree rooted at 3 is not a binary search tree, because its right child holds 2, which is smaller than 3. The best valid subtree is the single node holding 2.
Every valid subtree here is a single node with a negative key, so the empty subtree and its key sum of 0 win.