700. Search in a Binary Search Tree

bst: O(logn)

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

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)

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;
    }
}

Last updated