Validate Binary Search Tree
You get the root of a binary tree. Say whether it is a binary search tree: at every node, all values in the left subtree are smaller than the node and all values in the right subtree are larger. Our tree: 10 with children 5 and 15; 15 has children 6 and 20 — the answer is false: 6 is in the right subtree of 10 but smaller than 10.
- input
root: a binary tree, written as on LeetCode: its values level by level, left to right,nullfor a missing child.- returns
trueif it is a binary search tree: every value in a node's left subtree is less than the node's, every value in its right subtree greater (no value twice); otherwisefalse.- constraints
- 1 ≤ the number of nodes ≤ 1000
- −2³¹ ≤ Node.val ≤ 2³¹ − 1
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
function isValidBST(root) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more tree traversals problems
- 94Binary Tree Inorder TraversalEasysolve
- 144Binary Tree Preorder TraversalEasysolve
- 145Binary Tree Postorder TraversalEasysolve
- 530Minimum Absolute Difference in BSTEasysolve
- 230Kth Smallest Element in a BSTMediumsolve
- 114Flatten Binary Tree to Linked ListMediumsolve
- 173Binary Search Tree IteratorMediumsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.