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

Edge cases to test

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 node

C++

#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