oneby7

Binary Search Trees Using the ordering

395. Largest BST Subtree

Medium

You are given root, the root node of a binary tree. Find the largest subtree that is a binary search tree, and return the number of nodes in it.

A subtree is a node together with all of the nodes below it: its children, their children, and so on down to the leaves. It cannot leave any of them out. A subtree is a binary search tree (BST) when, at every node in it, every value in the node's left subtree is smaller than the node's value, and every value in its right subtree is larger. Values in the tree can repeat, but a subtree that holds two equal values is not a BST. A single node is a BST, and an empty tree has an answer of 0.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

36791412152025

Input: root = [12, 6, 20, 3, 9, 15, 25, null, null, 7, 14]

Output: 5

Explanation: The subtree under 6 holds 6, 3, 9, 7 and 14, and it is a BST. The whole tree is not, because 14 sits in the left subtree of 12 but is larger than 12. The subtree under 20 is a BST too, but it has only 3 nodes.

Example 2

335789

Input: root = [7, 3, 9, 3, 5, 8]

Output: 2

Explanation: The 3 under the root has another 3 as its left child, so its subtree is not a BST, and neither is the whole tree. The largest BST is 9 with its left child 8.

Example 3

−10⁹-7-510⁹

Input: root = [-5, -1000000000, 1000000000, null, -7]

Output: 4

Explanation: The whole tree is a BST, so all four nodes count.

Check your understanding

Work out the answer for this input before you write any code.

root = [10, 5, 15, 1, 12, null, 20]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.