zoukankan      html  css  js  c++  java
  • LeetCode-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.

    Analysis:

      Find the two values before and after the target. Use two integer to record the most recent two values.

    Solution:

      

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public class Pair {
    12         int val1;
    13         int val2;
    14 
    15         Pair(int v1, int v2) {
    16             val1 = v1;
    17             val2 = v2;
    18         }
    19     }
    20 
    21     public boolean closestValueRecur(TreeNode curNode, double target, Pair res) {
    22         if (curNode == null)
    23             return false;
    24 
    25         if (closestValueRecur(curNode.left, target, res))
    26             return true;
    27         res.val1 = res.val2;
    28         res.val2 = curNode.val;
    29         if (res.val1 <= target && res.val2 >= target)
    30             return true;
    31         if (closestValueRecur(curNode.right, target, res))
    32             return true;
    33 
    34         return false;
    35     }
    36 
    37     public int closestValue(TreeNode root, double target) {
    38         Pair res = new Pair(Integer.MIN_VALUE, Integer.MIN_VALUE);
    39 
    40         closestValueRecur(root, target, res);
    41 
    42         if (res.val1 == Integer.MIN_VALUE)
    43             return res.val2;
    44         if (res.val2 <= target)
    45             return res.val2;
    46 
    47         if (target - res.val1 < res.val2 - target)
    48             return res.val1;
    49         else
    50             return res.val2;
    51     }
    52 }
  • 相关阅读:
    Nunit单元测试实践
    win2003下安装大程序的补丁
    内存内运行vs05
    vs03无法调试,需要加入debugger组的办法
    js原型类样例
    DOS下建立以日期文件夹备份的批处理
    转flex了,ria的应用看上去很适合企业级应用开发呢
    C#类中使用Session的正确方法
    C#修改connectionStrings的方法
    批量更改目录或者文件名称
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5667153.html
Copyright © 2011-2022 走看看