Problem · Tree

Validate Binary Search Tree

Learn this problem
MediumTokopedia logoTokopediaFULLTIMEONSITE INTERVIEW

Problem statement

Given the root of a binary tree, return whether it is a valid binary search tree.

For every node, every value in its left subtree must be strictly smaller than the node's value, every value in its right subtree must be strictly greater, and both subtrees must satisfy the same rule. Duplicate values therefore make the tree invalid.

Function

isValidBST(root: TreeNode) → boolean

Examples

Example 1

root = [2,1,3]return = true

Both children satisfy the strict bounds imposed by the root.

Example 2

root = [5,1,4,null,null,3,6]return = false

Node 4 is in the root's right subtree but is smaller than root value 5.

Constraints

  • The tree contains between 1 and 10000 nodes.
  • -2147483648 <= Node.val <= 2147483647.

More Tokopedia problems

drafts saved locally
public boolean isValidBST(TreeNode root) {
    // Write your code here.
}
root[2,1,3]
expectedtrue
checking account