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 }
复制代码

跟上Closest Binary Search Tree Value II.

类似Search in a Binary Search Tree.

posted @   Dylan_Java_NYC  阅读(632)  评论(0编辑  收藏  举报
编辑推荐:
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
· 继承的思维:从思维模式到架构设计的深度解析
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
阅读排行:
· BotSharp + MCP 三步实现智能体开发
· 动物智能之数据标注员——狗篇
· 5. RabbitMQ 消息队列中 Exchanges(交换机) 的详细说明
· 设计模式脉络
· 「硬核实战」回调函数到底是个啥?一文带你从原理到实战彻底掌握C/C++回调函数
点击右上角即可分享
微信分享提示