【Leetcode】700. Search in a Binary Search Tree

题目地址:

https://leetcode.com/problems/search-in-a-binary-search-tree/

在二叉搜索树里搜索val值,若找到则返回该节点,否则返回null。
法1:

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

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

时间复杂度 O ( h ) O(h) O(h),空间 O ( 1 ) O(1) O(1)

法2:

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

时空复杂度 O ( h ) O(h) O(h)

你可能感兴趣的:(LC,树,分治与堆,leetcode,java,算法)