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 }
  • 相关阅读:
    洛谷 U141580 简化罗波切问题
    洛谷 U141578 维修电路
    洛谷 U140760 狭义公因子
    CF75C Modified GCD
    算法题-求解斐波那切数列的第N个数是几?
    算法题-求N的阶乘
    JAVA8新特性
    nginx启动脚本,手动编辑
    javah生成带有包名的头文件
    Matlab图像处理(03)-基本概念
  • 原文地址:https://www.cnblogs.com/joycelee/p/5340720.html
Copyright © 2011-2022 走看看