[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 ...
随机推荐
- 19_高级映射:一对多查询(使用resultMap)
[需求] 查询订单以及订单明细的信息. 确定主查询表:订单表orders 确定关联查询表:订单明细表 orderdetail 在一对一查询的基础上添加订单明细表关联即可. [分析] 使用resultM ...
- POJ 2127 Greatest Common Increasing Subsequence -- 动态规划
题目地址:http://poj.org/problem?id=2127 Description You are given two sequences of integer numbers. Writ ...
- poj 2533 Longest Ordered Subsequence 最长递增子序列
作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4098562.html 题目链接:poj 2533 Longest Ordered Subse ...
- c#通过反射获取类上的自定义特性
c#通过反射获取类上的自定义特性 本文转载:http://www.cnblogs.com/jeffwongishandsome/archive/2009/11/18/1602825.html 下面这个 ...
- IE6下input标签border问题
IE6下input标签的border的样式border:none;是不起作用的!要设置border:0px;才行!
- oracle LogMiner配置使用
一.安装LogMiner1.@D:\app\product\11.1.0\db_1\RDBMS\ADMIN\dbmslm.sql 2.@D:\app\product\11.1.0\db_1\RDBMS ...
- about building flying sauser
download flying sauser: unzip flyingsaucer-master.zip cd flyingsaucer-master/ mvn install
- 2014年度辛星css教程夏季版第五节
本小节我们讲解css中的”盒模型“,即”box model“,它通常用于在布局的时候使用,这个”盒模型“也有人成为”框模型“,其实原理都一样,它的大致原理是这样的,它把一个HTML元素分为了这么几个部 ...
- Extjs 更新数据集Ext.PagingToolbar的start参数重置的处理
问题:当翻页后,比如当前是第二页,start参数此时是5(初始为0),当切换左侧分类时,我们期望的是从所选分类下明细记录的第一条开始显示,结果发现不是这样,依然是从新数据的第二页开始显示,就是说ext ...
- SqlServer2008 设置修改表设计限制
我记起来了 SQL Server 2008 对操作的安全性进行了限制 你要在Management Studio菜单栏 -工具-选项,弹出选项窗口:把 “阻止保存要求重新创建表的更改” 请的勾去掉.