IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    270. Closest Binary Search Tree Value

    10k发表于 2023-08-09 00:00:00
    love 0

    Question

    Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest.

    Example 1:

    img

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

    Algorithm

    Easy question. Traverse the tree and compare and record the smallest absolute value from the target and the node value.

    Code

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        double min = Double.MAX_VALUE;
        int res;
        public int closestValue(TreeNode root, double target) {
            helper(root, target);
            return (int) res;
        }
        
        private void helper(TreeNode root, double target) {
            if (root == null) return;
            helper(root.left, target);
            if (Math.abs(target - root.val) < min) {
                min = Math.abs(target - root.val);
                res = root.val;
            }
            
            helper(root.right, target);
        }
    }
    


沪ICP备19023445号-2号
友情链接