LeetCode Solutions

700. Search in a Binary Search Tree

Time: $O(n)$

Space: $O(h)$

			

class Solution {
 public:
  TreeNode* searchBST(TreeNode* root, int val) {
    if (root == nullptr)
      return nullptr;
    if (root->val == val)
      return root;
    if (root->val > val)
      return searchBST(root->left, val);
    return searchBST(root->right, val);
  }
};
			

public class Solution {
  public TreeNode searchBST(TreeNode root, int val) {
    if (root == null)
      return null;
    if (root.val == val)
      return root;
    if (root.val > val)
      return searchBST(root.left, val);
    return searchBST(root.right, val);
  }
}
			

class Solution:
  def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
    if not root:
      return None
    if root.val == val:
      return root
    if root.val > val:
      return self.searchBST(root.left, val)
    return self.searchBST(root.right, val)