• 270. Closest Binary Search Tree Value


    Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

    Note:

    • Given target value is a floating point.
    • You are guaranteed to have only one unique value in the BST that is closest to the target.
     1 Solution 1. Iteration
     2 /**
     3  * Definition for a binary tree node.
     4  * public class TreeNode {
     5  *     int val;
     6  *     TreeNode left;
     7  *     TreeNode right;
     8  *     TreeNode(int x) { val = x; }
     9  * }
    10  */
    11 public class Solution {
    12     public int closestValue(TreeNode root, double target) {
    13         double diff = Double.MAX_VALUE;
    14         int val = root.val;
    15         
    16         while (root != null) {
    17             if (diff > Math.abs(root.val - target)) {
    18                 val = root.val;
    19                 diff = Math.abs(root.val - target);
    20             }
    21             if (root.val > target) {
    22                 root = root.left;
    23             } else {
    24                 root = root.right;
    25             }
    26         } 
    27         
    28         return val;
    29     }
    30 }
    31 
    32 Solution 2. Recursion
    33 public class Solution {
    34     public int closestValue(TreeNode root, double target) {
    35         int a = root.val;
    36         TreeNode kid = target < a ? root.left : root.right;
    37         if (kid == null) return a;
    38         int b = closestValue(kid, target);
    39         return Math.abs(a - target) < Math.abs(b - target) ? a : b;
    40     }    
    41 }
  • 相关阅读:
    MySQL权限详解
    MySql 详解
    顶级Python库
    第一次读到就震撼的句子
    Windows快捷键大全
    Pycharm超级好用的快捷键——效率之王
    Django框架
    前端入门和进阶必会
    正则表达式BREs,EREs,PREs的比较
    selenium模块基础用法详解
  • 原文地址:https://www.cnblogs.com/joycelee/p/5340720.html
Copyright © 2020-2023  润新知