Leetcode 272. Closest Binary Search Tree Value II
来源:互联网 发布:美国人工智能政策 编辑:程序博客网 时间:2024/06/05 20:48
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); }
阅读全文
0 0
- [Leetcode]Closest Binary Search Tree Value II
- [leetcode] 272. Closest Binary Search Tree Value II 解题报告
- LeetCode 272. Closest Binary Search Tree Value II
- Leetcode 272. Closest Binary Search Tree Value II (Hard) (cpp)
- Leetcode 272. Closest Binary Search Tree Value II
- [Leetcode] 272. Closest Binary Search Tree Value II 解题报告
- 272. Closest Binary Search Tree Value II
- leetcode 272: Closest Binary Search Tree Value II
- LeetCode 题解(250) : Closest Binary Search Tree Value II
- [LeetCode282]Closest Binary Search Tree Value II
- Closest Binary Search Tree Value II
- Closest Binary Search Tree Value II
- LeetCode 272. Closest Binary Search Tree Value II(二叉搜索树查找)
- [Leetcode]Closest Binary Search Tree Value
- leetcode 270: Closest Binary Search Tree Value
- *LeetCode-Closest Binary Search Tree Value
- [leetcode 270] Closest Binary Search Tree Value
- Leetcode 270Closest Binary Search Tree Value
- python高级编程-----类工厂(1)
- linux中目录信息查询ls命令的简单使用方法
- list,map,set的遍历以及排序
- 预警:传统的QA岗位将被DevOps淘汰
- kafka安装
- Leetcode 272. Closest Binary Search Tree Value II
- MySQL limit 分页查询数据库
- 剑指Offer----从尾到头打印链表
- 【机器学习杂货铺】——过拟合和欠拟合(暂缺)
- Java
- 对于大数(?)的是否为7的倍数的判断
- MFC下调用控制台
- Deis被微软收入囊中
- LeetCode之Find Bottom Left Tree Value