[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 ...
随机推荐
- 12天学好C语言——记录我的C语言学习之路(Day 5)
12天学好C语言--记录我的C语言学习之路 Day 5: 第五天的学习开始了,今天我们主要对几个程序进行编写,让自己充分的熟练编程语言,大量的题目会让自己变的精炼.以一个程序(program 5.1) ...
- C# .NET 获取枚举值的自定义属性(特性/注释/备注)信息
一.引言 枚举为我看日常开发的可读性提供的非常好的支持,但是有时我们需要得到枚举值得描述信息或者是注释(备注)信息 比如要获得 TestEmun.aaa 属性值得备注 AAA,比较不方便得到. pub ...
- 学习之spring注解DI疑惑
接口定义 package com; public interface IPaly { void say(); } 接口实现类 package com; import org.springframewo ...
- [PR & ML 2] [Introduction] Example: Polynomial Curve Fitting
啊啊啊,竟然不支持latex,竟然HTML代码不能包含javascript,代码编辑器也不支持Matlab!!!我要吐槽博客的编辑器...T_T只能贴图凑合看了,代码不是图,但这次为了省脑细胞,写的不 ...
- InstallShield : 如何查找编译后的 Merge Module存放路径
工程菜单栏中依次选择 Tools ---> Options… ,选择 Merge Modules tab 页,如下,就会看到Merge Module的存放路径,也可以根据需求修改. Merge ...
- Normalize.css:优化重置CSS默认属性
Normalize.css:优化重置CSS默认属性 官方网站:http://necolas.github.io/normalize.css/ 项目仓库:https://github.com/necol ...
- xml simpleXML_load_file(), simpleXML_load_string()
xml.xml文件 <?xml version='1.0'?><man> <att> <name>lin3615</name& ...
- (转载)SQL语句导入导出大全
SQL语句导入导出大全 /******* 导出到excel EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:\temp1.xls -c ...
- linux安装mysql出现Could NOT find Curses (missing CURSES_LIBRARY CURSES_INCLUDE_PATH),提示解决方法
[root@localhost mysql-5.5.11]# cmake . 出现以下错误提示: -- Could NOT find Curses (missing: CURSES_LIBRARY ...
- C语言小结之结构类型
C语言小结之结构类型 @刁钻的游戏 (1)枚举型类型enum COLOR {BLACK,RED,BLUE};//声明一种新的数据类型,其值分别为0,1,2但是用BLACK/RED/BLUE代表也可以这 ...