FastPrepValidate a Binary Search Tree

Validate a Binary Search Tree

NVIDIA logoNVIDIA● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

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

For this practice, every node in a left subtree must have a value strictly less than its ancestor, and every node in a right subtree must have a value strictly greater than its ancestor. This rule applies to every ancestor, not only to each node’s immediate children. Duplicate values make the tree invalid. An empty tree is valid.

Input examples use level-order array notation with null for missing children.

Function

isValidBST(root: TreeNode) → boolean

Examples

Example 1

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

The left value is smaller than 2 and the right value is greater.

Example 2

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

Value 3 lies in the root’s right subtree but is less than 5.

Example 3

root = [2,2,3]return = false

A duplicate value in the left child violates strict BST ordering.

Constraints

  • The tree contains 0 to 100 nodes.
  • -10^9 <= node.val <= 10^9.
  • Use strict inequalities for every subtree bound.

More NVIDIA problems

See NVIDIA hiring insights
public boolean isValidBST(TreeNode root) {
    // Write your code here.
}
root[2,1,3]
expectedtrue
Checking account…