270. Closest Binary Search Tree Value

Easy
这道题整理下思路,求the value in the BST that is closest to the target.那肯定要记录一个minDiff不用说吧,因为要返回的是node的val,所以肯定还得记录一个minDiffNode吧。之后再考虑一下怎么找,首先从根开始,然后肯定左右找。怎么确定往左往右,bst肯定就是比较target与根的大小关系.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        int minDiffNode = root.val;
        double minDiff = Math.abs(root.val - target);
        TreeNode curt = root;
        while (curt != null){
            double diff = Math.abs(curt.val - target);
            if (diff < minDiff){
                minDiff = diff;
                minDiffNode = curt.val;
            }
            if (curt.val < target){
                curt = curt.right;
            } else {
                curt = curt.left;
            }            
        }
        return minDiffNode;
    }
}

正好看面经题有个这个题的follow up, 给一个binary search tree,和target,返回树中大于target最小数字。其实就是这道题去掉小于target的数之后求出来的结果。

你可能感兴趣的:(270. Closest Binary Search Tree Value)