270. Closest Binary Search Tree Value 二叉搜索树中,距离目标值最近的节点

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.

 

Example 1:

270. Closest Binary Search Tree Value 二叉搜索树中,距离目标值最近的节点

Input: root = [4,2,5,1,3], target = 3.714286
Output: 4

Example 2:

Input: root = [1], target = 4.428571
Output: 1

 

复习时还不会的地方:我缺少了一个比较的过程。这种有大小的题是需要比大小的。node已经很大了就去左边寻找,
……小……右边

参考:https://leetcode.com/problems/closest-binary-search-tree-value/discuss/70322/Super-clean-recursive-Java-solution

public class Solution {
    public int closestValue(TreeNode root, double target) {
        return closest(root, target, root.val);
    }
    
    private int closest(TreeNode node, double target, int val) {
        if (node == null) return val;
        if (Math.abs(node.val - target) < Math.abs(val - target)) val = node.val;
        if (node.val < target) val = closest(node.right, target, val);
        else if (node.val > target) val = closest(node.left, target, val);
        return val;
    }
}
View Code
public class Solution {
    public int closestValue(TreeNode root, double target) {
        return closest(root, target, root.val);
    }
    
    private int closest(TreeNode node, double target, int val) {
        if (node == null) return val;
        if (Math.abs(node.val - target) < Math.abs(val - target)) val = node.val;
        if (node.val < target) val = closest(node.right, target, val);
        else if (node.val > target) val = closest(node.left, target, val);
        return val;
    }
}
View Code