zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    codeforces 587B
    codeforces 552E
    算法竞赛模板 字典树
    算法竞赛模板 二叉树
    算法竞赛模板 图形面积计算
    TZOJ 1545 Hurdles of 110m(动态规划)
    算法竞赛模板 判断线段相交
    算法竞赛模板 折线分割平面
    TZOJ 3005 Triangle(判断点是否在三角形内+卡精度)
    算法竞赛模板 KMP
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14975118.html
Copyright © 2011-2022 走看看