# 700. Search in a Binary Search Tree

{% embed url="https://leetcode.com/problems/search-in-a-binary-search-tree/" %}



bst: O(logn)

O(h),O(h)  h is the height of tree, avg: O(logn)

```java
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null || root.val == val) return root;

        if (val < root.val) {
            return searchBST(root.left, val);
        } else {
            return searchBST(root.right, val);
        }
        
    }
}
```

O(h),O(1)  h is the height of tree, avg: O(logn)

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