270. Closest Binary Search Tree Value

Tried to get this done recursively in the first place.

But then I realized I could not do that since the target coulde be larger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE, which made global res pretty hard to initialize...

I stopped trying and got this shit done iteratively....

public class Solution {
    
    public int closestValue(TreeNode root, double target) {
        if((double)root.val == target) return root.val;
        
        TreeNode temp = root;
        int res = root.val;
        while(true){
            if(Math.abs((double)res - target) > Math.abs((double)temp.val - target)) res = temp.val;
            if((double)temp.val > target){
                temp = temp.left;
            }else if((double)temp.val < target){
                temp = temp.right;
            }else return temp.val;
            if(temp == null) return res;
        }
        
    }
}

I was simply being stupid.
@StefanPochmann
This guy makes me feel sry for my uselessness.Even at an E problem.

int a = root.val;
    TreeNode kid = target < a ? root.left : root.right;
    if (kid == null) return a;
    int b = closestValue(kid, target);
    return Math.abs(a - target) < Math.abs(b - target) ? a : b;

我真心喜欢下面这种格式的代码

public class Solution 
{
    public int closestValue(TreeNode root, double target) 
    {
        TreeNode temp = root;
        TreeNode res = root;
        while(true)
        {
            if( Math.abs(target-(double)res.val)> Math.abs((double)temp.val-target)) res = temp;
            if((double)temp.val == target) return temp.val;
            else if((double)temp.val < target)
            {
                
                if(temp.right == null) break;
                temp = temp.right;
            }
            else
            {
                
                if(temp.left == null) break;
                temp = temp.left;
            }

        }
        return res.val;
    }
}

最上面那种都他妈挤在一起,看起来就想吐。

posted @ 2016-10-21 09:28  哇呀呀..生气啦~  阅读(128)  评论(0)    收藏  举报