zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Python 实践
    Keras实践
    NLP S实践
    Spark java 实践
    Seaborn数据探索可视化
    Linux实践
    Redis
    ML算法选型
    Elasticsearch issue
    牛客练习赛37
  • 原文地址:https://www.cnblogs.com/joycelee/p/5340720.html
Copyright © 2011-2022 走看看