Practice › Trees
Validate Binary Search Tree
Medium · Trees · Asked at Amazon, Microsoft, Google, Bloomberg
Print YES if the tree is a valid BST: every node is strictly greater than all values in its left subtree and strictly smaller than all values in its right subtree. Otherwise print NO.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node.
Output
YES or NO.
Constraints
- 1 ≤ number of nodes ≤ 10^4
- 1 ≤ value ≤ 10^9
Checking only parent and child is not enough — pass down a valid (min, max) range.
Example 1
Input
3 2 1 3
Output
YES
Example 2
Input
7 5 1 4 -1 -1 3 6
Output
NO
Hints
- Checking only "left child < node < right child" misses cases like a small value deep in the right subtree.
- Pass down the allowed open range (low, high). Going left narrows high to node.val; going right narrows low to node.val.
Approach
valid(node, low, high): an empty node is valid. Otherwise the node needs low < val < high (strict), its left subtree must be valid in (low, val) and its right subtree in (val, high). Start with (−∞, +∞). Another way: an inorder traversal of a valid BST is strictly increasing.
Complexity: O(n) time · O(h) recursion depth
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// Build a tree from level order where -1 means "no node".
Node *readTree() {
int k;
cin >> k;
vector<long long> v(k);
for (auto &x : v) cin >> x;
if (k == 0 || v[0] == -1) return nullptr;
Node *root = new Node(v[0]);
queue<Node *> q;
q.push(root);
int i = 1;
while (!q.empty() && i < k) {
Node *cur = q.front();
q.pop();
if (i < k && v[i] != -1) q.push(cur->left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.push(cur->right = new Node(v[i]));
i++;
}
return root;
}
bool valid(Node *node, long long low, long long high) {
if (!node) return true;
if (node->val <= low || node->val >= high) return false;
return valid(node->left, low, node->val) && valid(node->right, node->val, high);
}
int main() {
cout << (valid(readTree(), LLONG_MIN, LLONG_MAX) ? "YES" : "NO") << "\n";
return 0;
}Python solution
import sys
from collections import deque
sys.setrecursionlimit(100000)
class Node:
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def read_tree():
"""Build a tree from level order where -1 means "no node"."""
data = list(map(int, sys.stdin.read().split()))
k, v = data[0], data[1 : data[0] + 1]
if not v or v[0] == -1:
return None
root = Node(v[0])
q, i = deque([root]), 1
while q and i < k:
cur = q.popleft()
if i < k and v[i] != -1:
cur.left = Node(v[i])
q.append(cur.left)
i += 1
if i < k and v[i] != -1:
cur.right = Node(v[i])
q.append(cur.right)
i += 1
return root
def valid(node, low, high):
if node is None:
return True
if not low < node.val < high:
return False
return valid(node.left, low, node.val) and valid(node.right, node.val, high)
print("YES" if valid(read_tree(), float("-inf"), float("inf")) else "NO")Java solution
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// Build a tree from level order where -1 means "no node".
static Node readTree(Scanner sc) {
int k = sc.nextInt();
long[] v = new long[k];
for (int i = 0; i < k; i++) v[i] = sc.nextLong();
if (k == 0 || v[0] == -1) return null;
Node root = new Node(v[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < k) {
Node cur = q.poll();
if (i < k && v[i] != -1) q.add(cur.left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.add(cur.right = new Node(v[i]));
i++;
}
return root;
}
static boolean valid(Node node, long low, long high) {
if (node == null) return true;
if (node.val <= low || node.val >= high) return false;
return valid(node.left, low, node.val) && valid(node.right, node.val, high);
}
public static void main(String[] args) {
Node root = readTree(new Scanner(System.in));
System.out.println(valid(root, Long.MIN_VALUE, Long.MAX_VALUE) ? "YES" : "NO");
}
}Solve Validate Binary Search Tree online · All practice problems