Cloest Binary Search Tree Value II

本文介绍了一种高效的算法,用于在二叉搜索树中找到与目标值最接近的K个整数值。该算法通过初始化两个栈分别追踪前驱节点和后继节点,然后比较两栈顶节点的值与目标值的距离来确定添加哪个值到结果列表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 List<Integer> closestKValues(TreeNode root, double target, int k) {
12         List<Integer> result = new ArrayList<>();
13         if (k == 0 || root == null) {
14             return result;
15         }
16         
17         Stack<TreeNode> successor = new Stack<>();
18         Stack<TreeNode> precessor = new Stack<>();
19         
20         initialStack(successor, root, true, target);
21         initialStack(precessor, root, false, target);
22         
23         if(!successor.isEmpty() && !precessor.isEmpty() && successor.peek().val == precessor.peek().val) {
24             getNext(precessor, false);
25         }
26         
27         while (result.size() < k) {
28             if (successor.isEmpty()) {
29                 result.add(getNext(precessor, false));
30             } else if (precessor.isEmpty()) {
31                 result.add(getNext(successor, true));
32             } else {
33                 boolean sclose = Math.abs((double) successor.peek().val - target) < Math.abs((double)precessor.peek().val - target);
34                 if (sclose) {
35                     result.add(getNext(successor, true));
36                 } else {
37                     result.add(getNext(precessor, false));
38                 }
39             }
40         }
41         return result;
42     }
43     
44     private void initialStack(Stack<TreeNode> stack, TreeNode root, boolean successor, double target) {
45         while (root != null) {
46             if (root.val == target) {
47                 stack.push(root);
48                 break;
49             } else if (root.val > target == successor) {
50                 stack.push(root);
51                 root = successor ? root.left : root.right;
52             } else {
53                 root = successor ? root.right : root.left;
54             }
55         }
56     }
57     
58     private int getNext(Stack<TreeNode> stack, boolean successor) {
59         TreeNode current = stack.pop();
60         int result = current.val;
61         current = successor ? current.right : current.left;
62         while (current != null) {
63             stack.push(current);
64             current = successor ? current.left : current.right;
65         }
66         return result;
67     }
68 }

 

转载于:https://www.cnblogs.com/shuashuashua/p/5723603.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值