[LeetCode#272] Closest Binary Search Tree Value II
Problem:
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)?
Analysis:
This problem is not hard. But the description of the problem is really quite misleading. It strongly hints you to use the characteristics of balance tree. I fail to achieve that. But there is also a very innovative and efficient way to solve this problem. Ask: Where are closest nodes of a give number ?
The predecessors and successors of a given number are the best candidates for you to choice, based on how many closest nodes you want.
And we already know through a inorder traversal we shoud easily get the tree in sorted form. It's really easy for us to find the closestKValues in the sorted form.
1 2 3 5 6 [target: 7] 8 10 23 25 But for this problem, we could solve it in more elegant way. Use the idea we have used in merging k sorted list.
Predecessors list: 6 5 3 2 1
Successors: 8 10 23 25 Basic knowledge enhancement
Through ordinary preorder traversal (scan left subtree first), we could get the binary search tree in the ascending order.
1 2 3 5 6 8 10 23 25
Through reverse preorder traversal (scan right subtree first), we could get the binary search tree in the descending order.
25 23 10 8 6 5 3 2 1 Step 1: get the predecessors list : 6 5 3 2 1 (descending order), through a stack.
------------------------------------------------------------------------
preOrderTraversal(is_reverse ? root.left, target, stack, is_reverse);
...
stack.push(root.val)
preOrderTraversal(is_reverse ? root.right, target, stack, is_reverse);
------------------------------------------------------------------------ Step 2: get the successors list : 8 10 23 25 (ascending order), through a stack.
------------------------------------------------------------------------
preOrderTraversal(is_reverse ? root.right, target, stack, is_reverse);
...
stack.push(root.val)
preOrderTraversal(is_reverse ? root.left, target, stack, is_reverse);
------------------------------------------------------------------------ A skill in getting "6 5 3 2 1" rather than "25 23 10 8 6 5 3 2 1".
if ((!is_reverse && root.val > target))
return;
//Great during the traversal process, we stop when we reach a node larger than target. A skill in getting "8 10 23 25" rahter than "25 23 10 8 6 5 3 2 1"
if (is_reverse && root.val <= target)
return;
Note: we use the same termination skill at here. Another skill to be careful (note when there is a stack was used up)
if (pre.isEmpty()) {
ret.add(suc.pop());
} else if (suc.isEmpty()) {
ret.add(pre.pop());
}
You must detect and handle above cases.
Solution:
public class Solution {
public List<Integer> closestKValues(TreeNode root, double target, int k) {
List<Integer> ret = new ArrayList<Integer> ();
Stack<Integer> pre = new Stack<Integer> ();
Stack<Integer> suc = new Stack<Integer> ();
preOrderTraversal(root, target, pre, false);
preOrderTraversal(root, target, suc, true);
int count = 0;
while (count < k) {
if (pre.isEmpty()) {
ret.add(suc.pop());
} else if (suc.isEmpty()) {
ret.add(pre.pop());
} else if (Math.abs(target - pre.peek()) < Math.abs(target - suc.peek())) {
ret.add(pre.pop());
} else {
ret.add(suc.pop());
}
count++;
}
return ret;
} private void preOrderTraversal(TreeNode root, double target, Stack<Integer> stack, boolean is_reverse) {
if (root == null)
return;
preOrderTraversal(is_reverse ? root.right : root.left, target, stack, is_reverse);
if ((is_reverse && root.val <= target) || (!is_reverse && root.val > target))
return;
stack.push(root.val);
preOrderTraversal(is_reverse ? root.left : root.right, target, stack, is_reverse);
}
}
[LeetCode#272] Closest Binary Search Tree Value II的更多相关文章
- [LeetCode] 272. Closest Binary Search Tree Value II 最近的二叉搜索树的值 II
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- [LeetCode] 272. Closest Binary Search Tree Value II 最近的二分搜索树的值之二
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- [leetcode]272. Closest Binary Search Tree Value II二叉搜索树中最近的值2
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- 272. Closest Binary Search Tree Value II
题目: Given a non-empty binary search tree and a target value, find k values in the BST that are close ...
- LC 272. Closest Binary Search Tree Value II 【lock,hard】
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- [Locked] Closest Binary Search Tree Value & Closest Binary Search Tree Value II
Closest Binary Search Tree Value Given a non-empty binary search tree and a target value, find the ...
- [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- LeetCode Closest Binary Search Tree Value II
原题链接在这里:https://leetcode.com/problems/closest-binary-search-tree-value-ii/ 题目: Given a non-empty bin ...
- [Swift]LeetCode272. 最近的二分搜索树的值 II $ Closest Binary Search Tree Value II
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
随机推荐
- 常用Linux/Unix/Mac Os命令
常用Linux/Unix/Mac OS命令 参考: 1.50 Most Frequently Used UNIX / Linux Commands (With Examples)
- C++ 中的“ !” 运算
在介绍“ !”运算之前,我们要知道一个变量n,如果n>0,那么我们可以在逻辑上叫它“真”,如果n<=0 ,那么我们可以在逻辑上叫它“假”. n为真时,!n就为假(false),转换为整型值 ...
- 【原创】开机出现grub rescue,修复办法
出现这种问题 一般在于进行了磁盘分区(GHOST备份时也会造成)导致grub引导文件找不到.我们只要让它找到引导文件就好了. 此时屏幕上提示grub resume> 我们先输入set看下现在g ...
- Asp.net 导入Excel数据
前台代码: <body> <form id="form1" runat="server"> <div> <asp:Fi ...
- Activity组件
Activity 间书作者:阿敏其人 关于Activity博文上 间书作者:阿敏其人 关于Activity博文中 间书作者:阿敏其人 关于Activity博文下
- 免费使用的图表控件XML/SWF Charts 5.08
免费使用的图表控件XML/SWF Charts 5.08 http://www.pin5i.com/showtopic-26053.html 10个免费的在线统计图表工具 http://paranim ...
- linux点滴:rsync
rsync(remote sync)是一款远程同步工具,可以实现全量备份.增量备份.本地备份.删除,核心功能是远程数据备份. 工作原理 rsync核心算法 1.分块checksum算法 首先,把文件平 ...
- 利用数据库链做DML操作时报ORA-02069: global_names parameter must be set to TRUE for this operation
按照 http://space.itpub.net/195110/viewspace-711110 的说法顺利解决问题. 通过DBLink更新远程数据的时候,如果使用到本地的sequence.函数.过 ...
- c# 判断窗体是否永在最前(TopMost),调用windows API
许多程序都可以把自身的窗体设为最前显示状态,这个可以参考博客c#让窗体永在最前 调用windows api 将窗体设为topmost.那么如何判断桌面上的一个窗体是否为最前显示状态呢,不光是自己的程序 ...
- easyui 汉化问题
遇到 easyui 需要汉化的 , 1: 找到 汉化文件 ,文件位于 插件的 locale 文件夹 内 easyui-lang-zh_CN.js 2: 将其 加载 与 easyui 之后 <s ...