码迷,mamicode.com
首页 > 其他好文 > 详细

*Closest Binary Search Tree Value

时间:2016-01-06 06:48:38      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

 

 

 

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

 

*Closest Binary Search Tree Value

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5104289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!