博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Closest Binary Search Tree Value
阅读量:6402 次
发布时间:2019-06-23

本文共 1361 字,大约阅读时间需要 4 分钟。

Problem Description:

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.

Well, this problem can be solved easily using recursion: just find the closest value in the left and right subtrees and compare them with root -> val. The code is as follows.

1 class Solution { 2 public: 3     int closestValue(TreeNode* root, double target) { 4         if (!root) return INT_MAX; 5         if (!(root -> left) && !(root -> right)) return root -> val; 6         int left = closestValue(root -> left, target); 7         int right = closestValue(root -> right, target); 8         double td = abs(root -> val - target), ld = abs(left - target), rd = abs(right - target); 9         if (td < ld) return td < rd ? root -> val : right;10         else return ld < rd ? left : right;11     }12 };

Notice that in the above code the properties of BST have not been used. So, what do you think? Well, the above code can be extended to Closest Binary Tree Value if this problem is published in the future :-) Well, Stefan posts several solutions (including a shorter C++ one) in 4 languages . So, refer to them and get more fun :-)

转载于:https://www.cnblogs.com/jcliBlogger/p/4763200.html

你可能感兴趣的文章
es6基础0x014:WeakMap
查看>>
九种 “姿势” 让你彻底解决跨域问题
查看>>
php中mysqli 处理查询结果集总结
查看>>
你不知道的JavaScript运算符
查看>>
小程序开发注意事项
查看>>
ECMAScript7规范中的instanceof操作符
查看>>
Hadoop HDFS原理分析
查看>>
【webpack4】基本配置和入门api
查看>>
Mac使用ssh公钥登录Linux
查看>>
【366天】跃迁之路——程序员高效学习方法论探索系列(实验阶段124-2018.02.06)...
查看>>
POJ3070-Fibonacci(矩阵快速幂)
查看>>
[vue插件]基于vue2.x的电商图片放大镜插件
查看>>
标准的组件结构
查看>>
vue——一个页面实现音乐播放器
查看>>
SVG 扬帆起航
查看>>
NET Core-学习笔记(二)
查看>>
职业生涯上的点点滴滴
查看>>
Linux下添加新硬盘,分区及挂载
查看>>
一起来将vscode变成私人定制笔记本
查看>>
Flutter 云音乐
查看>>