【Lintcode】1524. Search in a Binary Search Tree

题目地址:

https://www.lintcode.com/problem/search-in-a-binary-search-tree/description

给定一棵BST和一个数target,寻找值等于target的node。代码如下:

public class Solution {
    /**
     * @param root: the tree
     * @param val: the val which should be find
     * @return: the node
     */
    public TreeNode searchBST(TreeNode root, int val) {
        // Write your code here.
        while (root != null && root.val != val) {
            root = root.val < val ? root.right : root.left;
        }
        
        return root;
    }
}

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

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

发布了387 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105465251