Leetcode 272. Closest Binary Search Tree Value II

本文介绍了一种算法,用于在非空二叉搜索树中找到最接近指定目标值的K个节点值。该算法利用了两个栈分别收集比目标值小和大的节点值,并比较它们与目标的距离来选取最接近的K个值。

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

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.

Note:

  • Given target value is a floating point.
  • You may assume k is always valid, that is: k ≤ total nodes.
  • You are guaranteed to have only one unique set of k values in the BST that are closest to the target.

Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        List<Integer> res = new ArrayList<>();
        Stack<Integer> s1 = new Stack<>(); 
        Stack<Integer> s2 = new Stack<>();
        get_predecessor(root, target, s1);
        get_successor(root, target, s2);

        while (k-- > 0) {
            if (s1.isEmpty()) res.add(s2.pop());
            else if (s2.isEmpty()) res.add(s1.pop());
            else if (Math.abs(s1.peek() - target) < Math.abs(s2.peek() - target)) res.add(s1.pop());
            else res.add(s2.pop());
        }
        return res;
    }
    
    private void get_predecessor(TreeNode root, double target, Stack<Integer> s1) {
        if (root == null) return;
        get_predecessor(root.left, target, s1);
        if (root.val > target) return;
        s1.push(root.val);
        get_predecessor(root.right, target, s1);
    }
    
    private void get_successor(TreeNode root, double target, Stack<Integer> s2) {
        if (root == null) return;
        get_successor(root.right, target, s2);
        if (root.val <= target) return;
        s2.push(root.val);
        get_successor(root.left, target, s2);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值