Instructions
You are given the root of a binary tree. Find the largest subtree that is a valid binary search tree (BST), and return its number of nodes.
- A subtree here is a node together with all of its descendants. You cannot leave out some of the nodes below it.
- A subtree is a valid BST when, for every node in it, every value in its left subtree is strictly smaller than the node's value and every value in its right subtree is strictly larger. Equal values are not allowed.
- A single node is always a valid BST, so a non-empty tree has an answer of at least
1. For an empty tree, return0.
How the input is shown
The tree is written in level order: the values row by row, from left to right, with null where a child is missing. For example, [1, 2, 3, null, 4] is the root 1 with children 2 and 3, and 4 is the right child of 2. Your function gets the TreeNode root (or null / None for an empty tree), with fields val, left and right.
Hint
Checking a node against its two children only is not enough: a value deep in the left subtree can still be too large. Work from the bottom up. Let each node return whether its subtree is a BST, its size, and its smallest and largest values. Then a node can decide about itself in O(1).
Examples
Example 1
- Input:
- [6,3,9,1,7]
- Output:
- 3
Node 3 with its children 1 and 7 is a valid BST (1 < 3 < 7), so it has 3 nodes. The whole tree is not a BST: 7 is in the left subtree of 6 but is larger than 6. No subtree has more than 3 nodes and is valid.
Example 2
- Input:
- [4,4,6]
- Output:
- 1
The whole tree is not a BST because the left child 4 is equal to the root 4, and equal values are not allowed. The best subtrees are the single nodes 4 and 6, each with 1 node.
Example 3
- Input:
- [20,11,34,5,16,28,41]
- Output:
- 7
The whole tree is a valid BST, so the answer is all 7 nodes.
Constraints
- The tree has between
0and40nodes. -50 <= Node.val <= 50(values can repeat).
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [6,3,9,1,7]
- Expected:
- 3
- Input:
- [4,4,6]
- Expected:
- 1
- Input:
- [20,11,34,5,16,28,41]
- Expected:
- 7
Run checks your code against the 3 examples. Submit checks it against all 163 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.