【Lintcode】1524. Search in a Binary Search Tree

Title address:

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

Given a BST and a number target, find the node whose value is equal to target. code show as below:

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

time complexity THE ( h ) O(h)

Published 387 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105465251