LeetCode 700: Search in a Binary Search Tree Solution

Master LeetCode problem 700 (Search in a Binary Search Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

700. Search in a Binary Search Tree

Problem Explanation

Explanation

To solve this problem, we will perform a simple binary search on the BST. Starting from the root node, we will compare the value with the given target value. If the current node's value is equal to the target value, we return the current node. If the target value is less than the current node's value, we move to the left subtree. If the target value is greater than the current node's value, we move to the right subtree. We repeat this process until we find the target value or reach a leaf node.

  • Algorithm:

    1. Start from the root node.
    2. If the current node is null, return null.
    3. If the current node's value is equal to the target value, return the current node.
    4. If the target value is less than the current node's value, move to the left subtree.
    5. If the target value is greater than the current node's value, move to the right subtree.
    6. Repeat steps 2-5 until we find the target value or reach a leaf node.
  • Time Complexity: O(log N) on average, where N is the number of nodes in the BST.

  • Space Complexity: O(1) since we are using iterative traversal.

Solution Code

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        while (root != null && root.val != val) {
            root = (val < root.val) ? root.left : root.right;
        }
        return root;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 700 (Search in a Binary Search Tree)?

This page provides optimized solutions for LeetCode problem 700 (Search in a Binary Search Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 700 (Search in a Binary Search Tree)?

The time complexity for LeetCode 700 (Search in a Binary Search Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 700 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 700 in Java, C++, or Python.

Back to LeetCode Solutions