< Back





700. Search in a Binary Search Tree

Given a binary search tree, we have to find the node with the given value and return its subtree.
We can do this iteratively, using DFS but only traversing nodes following the binary search method.

The solution is as follows:


  class Solution:
      def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
          while root and root.val != val:
              root = root.left if val < root.val else root.right
          return root


_ Time Complexity:

  O(h) - Where h is the height of the tree.

_ Space Complexity:

  O(1) - We only maintain one pointer, using constant space.