其他分享
首页 > 其他分享> > 900. 二叉搜索树中最接近的值  

900. 二叉搜索树中最接近的值  

作者:互联网

900. 二叉搜索树中最接近的值

  给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值

样例

样例1 输入: root = {5,4,9,2,#,8,10} and target = 6.124780 输出: 5 解释: 二叉树 {5,4,9,2,#,8,10},表示如下的树结构: 5 / \ 4 9 / / \ 2 8 10 样例2 输入: root = {3,2,4,1} and target = 4.142857 输出: 4 解释: 二叉树 {3,2,4,1},表示如下的树结构: 3 / \ 2 4 / 1

注意事项

  public class Solution {     /**      * @param root:   the given BST      * @param target: the given target      * @return: the value in the BST that is closest to the target      */     public int closestValue(TreeNode root, double target) {         // write your code here         getValue(root, target);         return ret;     }         int ret = 0;     double min = Integer.MAX_VALUE;         private void getValue(TreeNode root, double target) {         if (root == null) return;         if (root.val < target) {             double temp = target - root.val;             if (temp < min) {                 ret = root.val;                 min = temp;             }             if (min < 0.5) {                 return;             }             getValue(root.right, target);         } else {             double temp = root.val - target;             if (temp < min) {                 ret = root.val;                 min = temp;             }             if (min < 0.5) {                 return;             }             getValue(root.left, target);         }     } }  

标签:900,return,target,temp,min,树中,二叉,val,root
来源: https://blog.csdn.net/xwdrhgr/article/details/117318873