Practice › Trees
Search in a BST
Easy · Trees · Asked at Amazon, Microsoft, Apple
The tree is a binary search tree. Print YES if x is stored in it, otherwise NO. Use the BST property — do not visit every node.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node. Third line: x.
Output
YES or NO.
Constraints
- 1 ≤ number of nodes ≤ 10^4
- All values are distinct
Go left if x is smaller than the current value, right if larger.
Example 1
Input
5 4 2 7 1 3 2
Output
YES
Example 2
Input
5 4 2 7 1 3 5
Output
NO
Hints
- In a BST everything left of a node is smaller and everything right is larger.
- Walk from the root: go left if x is smaller, right if larger, stop if equal or null.
Approach
A single root-to-leaf walk: at each node compare x with the value and move to one child. You never need to visit the other subtree, so the cost is the tree height, not n.
Complexity: O(h) time · O(1) space
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;
}
int main() {
Node *cur = readTree();
long long x;
cin >> x;
while (cur && cur->val != x) cur = x < cur->val ? cur->left : cur->right;
cout << (cur ? "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 build_tree(v):
"""Build a tree from level order where -1 means "no node"."""
if not v or v[0] == -1:
return None
root = Node(v[0])
q, i = deque([root]), 1
while q and i < len(v):
cur = q.popleft()
if i < len(v) and v[i] != -1:
cur.left = Node(v[i])
q.append(cur.left)
i += 1
if i < len(v) and v[i] != -1:
cur.right = Node(v[i])
q.append(cur.right)
i += 1
return root
data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = build_tree(data[1 : 1 + k])
rest = data[1 + k :]
x, cur = rest[0], root
while cur and cur.val != x:
cur = cur.left if x < cur.val else cur.right
print("YES" if cur 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;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Node cur = readTree(sc);
long x = sc.nextLong();
while (cur != null && cur.val != x) cur = x < cur.val ? cur.left : cur.right;
System.out.println(cur != null ? "YES" : "NO");
}
}