Skip to the code
cf.
+50 XP

#352 Largest Sorted Section

hard

A cache index was supposed to be a binary search tree, but parts of it got corrupted. You want to keep the biggest subtree that is still a valid search tree. A subtree means a node together with all of its descendants.

Write largestSortedSubtree(root) that returns the number of nodes in the largest subtree that is a valid binary search tree (every left descendant strictly smaller, every right descendant strictly bigger, at every node). An empty tree returns 0.

Example 1

Input: root = [10,5,15,1,8,null,7]
Output: 3

The subtree 5 (1, 8) is valid. The whole tree isn't, because 7 sits right of 15.

Example 2

Input: root = [2,1,3]
Output: 3

The whole tree is a valid search tree.

Constraints

  • 0 <= number of nodes <= 10^4
  • -10^4 <= value <= 10^4

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).