*Closest Binary Search Tree Value

 

 

 

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

 

public class Solution {
    public int closestValue(TreeNode root, double target) 
    {
        int closestVal = root.val;
        while(root!=null)
        {
            closestVal = (Math.abs(target-root.val) < Math.abs(target-closestVal))? root.val:closestVal;
            if(closestVal == target) return root.val;
            root = (root.val > target)? root.left:root.right;
            
        }
        return closestVal;
        
    }
}

 

posted @ 2016-01-06 06:24  Hygeia  阅读(121)  评论(0编辑  收藏  举报