LeetCode 270. Closest Binary Search Tree Value
原题链接在这里:https://leetcode.com/problems/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.
题解:
target 一定在找的path 上,若是出现了比minDiff 还小的差值,就把改点更新为cloest.
Time Complexity: O(h). h 是树的高度.
Space: O(1).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public int closestValue(TreeNode root, double target) { 18 int closest = root.val; 19 while(root != null){ 20 if(Math.abs(root.val - target) < Math.abs(closest - target) || (Math.abs(root.val - target) == Math.abs(closest - target) && root.val < target)){ 21 closest = root.val; 22 } 23 24 if(root.val < target){ 25 root = root.right; 26 }else if(root.val > target){ 27 root = root.left; 28 }else{ 29 return root.val; 30 } 31 } 32 return closest; 33 } 34 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
· 继承的思维:从思维模式到架构设计的深度解析
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· BotSharp + MCP 三步实现智能体开发
· 动物智能之数据标注员——狗篇
· 5. RabbitMQ 消息队列中 Exchanges(交换机) 的详细说明
· 设计模式脉络
· 「硬核实战」回调函数到底是个啥?一文带你从原理到实战彻底掌握C/C++回调函数