• 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:

    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
  • 相关阅读:
    selenium iframe 定位 qq空间说说
    单个 进程网速 消耗 网路 带宽
    网页加速
    baidu 验证网站 一一映射
    内容原发网站seo不重视2个标签,导致seo效果不如转发网站
    vi shell 的水平 决定了 手机shell 办公的效率
    键盘控制鼠标
    seo 谷歌去年悄然收购这家英国硬件公司
    视频 爬虫
    python 深浅 拷贝
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14975118.html
Copyright © 2020-2023  润新知