Algo-Sim › Binary Trees & BST
Search in a Binary Search Tree
Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input
Compare and go left or right: each step discards a whole subtree, so the search costs the height, not n.
Problem
Given the root of a binary search tree and a value val, return the subtree rooted at the node holding val, or null if no node holds it.
Constraints
- 1 ≤ number of nodes ≤ 5000
- 1 ≤ Node.val, val ≤ 10⁷
- The tree is a valid BST
- Cost is O(height), not O(n)
Edge cases to test
- Empty tree
- The value is the root
- The value is missing
Follow-up questions
- What is the worst case?
- O(n) on a skewed tree; a balanced BST (AVL, red–black) keeps it O(log n).
- How do you find the closest value?
- Walk down the same path, keeping the best candidate seen (LC 270).
Solution
Java
public TreeNode searchBST(TreeNode root, int val) {
TreeNode node = root;
while (node != null && node.val != val) {
node = val < node.val ? node.left : node.right;
}
return node;
}Python
def search_bst(root, val):
node = root
while node and node.val != val:
node = node.left if val < node.val else node.right
return nodeC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
TreeNode *searchBST(TreeNode *root, int val) {
TreeNode *node = root;
while (node != nullptr && node->val != val) {
node = val < node->val ? node->left : node->right;
}
return node;
}
};
More Binary Trees & BST problems
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)