Instructions
You are given the root of a binary tree. Return true if it is a valid binary search tree (BST), and false if it is not.
A tree is a valid BST when every node follows these rules:
- all values in its left subtree are smaller than the node's value;
- all values in its right subtree are larger than the node's value;
- its left subtree and its right subtree are valid BSTs too.
Note
- The rule is strict. A value equal to an ancestor's value makes the tree invalid.
- It is not enough to compare a node with its own children. A node deep in the left subtree of the root must also be smaller than the root.
- An empty tree and a tree with one node are valid.
- Values can be as small as
-2^31and as large as2^31 - 1. Be careful if you use these numbers as "no limit" markers.
How the input is shown
A tree is shown as a list of values in level order: row by row from the top, and left to right in each row. null means "no child here", and nulls at the end are left out. For example, [4, 2, 7, null, 3] is a root 4 with left child 2 and right child 7, and 2 has only a right child, 3.
Your function receives the root as a TreeNode (fields val, left, right), or null for an empty tree.
Hint: pass down a lower limit and an upper limit for each node. Or walk the tree in order (left, node, right) and check that the values only go up.
Examples
Example 1
- Input:
- [20,10,30,5,15,25,40]
- Output:
- true
Every value left of 20 (10, 5, 15) is smaller than 20, and every value right of it (30, 25, 40) is larger. The same is true at 10 and at 30.
Example 2
- Input:
- [20,10,30,5,25]
- Output:
- false
Node 25 is the right child of 10, and 25 > 10, so it is fine next to its parent. But 25 is in the left subtree of the root 20, and 25 is larger than 20. So the tree is not a BST.
Example 3
- Input:
- [7,7]
- Output:
- false
The left child has the same value as the root. Values on the left must be strictly smaller, so this is not a valid BST.
Constraints
- The number of nodes is between
0and35. -2^31 <= Node.val <= 2^31 - 1
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [20,10,30,5,15,25,40]
- Expected:
- true
- Input:
- [20,10,30,5,25]
- Expected:
- false
- Input:
- [7,7]
- Expected:
- false
Run checks your code against the 3 examples. Submit checks it against all 183 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.