原题网址:https://leetcode.com/problems...

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)?

Hint:

Consider implement these two helper functions:

getPredecessor(N), which returns the next smaller node to N.
getSuccessor(N), which returns the next larger node to N.

Try to assume that each node has a parent pointer, it makes the problem much easier.

Without parent pointer we just need to keep track of the path from the root to the current node using a stack.

You would need two stacks to track the path in finding predecessor and successor node separately.

题意:在二叉搜索树当中找到离target最近的K个数。

解题思路:
由于二叉搜索数的inorder中序遍历是有序的,比如例子中的树,中序遍历为[1,2,3,4,5]。我们可以利用这一特性,初始化一个双端队列Deque,用来存放k个数,然后用递归的方式,先走到the most left(也就是例子中的1),不断的向Deque中加入元素,直到元素装满,也就是Deque的size()到k个了,将当前元素与target的距离和队列头部与target的距离进行对比,如果当前元素的距离更小,则用Deque的pollFirst()方法将头部吐出,把当前元素从addLast()加入。

Example:Input: root = [4,2,5,1,3], target = 3.714286, and k = 24/ \2   5/ \
1   3Output: [4,3]

代码如下:

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/
class Solution {/***直接在中序遍历的过程中完成比较,当遍历到一个节点时,如果此时结果数组不到k个,我们直接将此节点值加入res中,如果该节点值和目标值的差值的绝对值小于res的首元素和目标值差值的绝对值,说明当前值更靠近目标值,则将首元素删除,末尾加上当前节点值,反之的话说明当前值比res中所有的值都更偏离目标值,由于中序遍历的特性,之后的值会更加的遍历,所以此时直接返回最终结果即可,*/public List<Integer> closestKValues(TreeNode root, double target, int k) {Deque<Integer> deque = new ArrayDeque<>();inorder(root, target, k, deque);List<Integer> res = new ArrayList<>(deque);return res;}private void inorder(TreeNode root, double target, int k, Deque<Integer> deque) {if (root == null) return;inorder(root.left, target, k, deque);if (deque.size() < k) {deque.offer(root.val);} else if (Math.abs(root.val - target) < Math.abs(deque.peekFirst()-target) ) {deque.pollFirst();deque.addLast(root.val);} inorder(root.right, target, k, deque);}
}

还有一种用Stack完成的方式,思路和递归相同,但是iterative的写法,也有必要掌握,必须把控Stack是否为空的情况,当前的node为null,但是stack中仍然有元素,依然需要进行比较。

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/
class Solution {public List<Integer> closestKValues(TreeNode root, double target, int k) {Deque<Integer> deque = new ArrayDeque<>();Stack<TreeNode> stack = new Stack<>();TreeNode cur = root;while(cur != null || !stack.isEmpty()) {while(cur != null) {stack.push(cur);cur = cur.left;}cur = stack.pop();if (deque.size() < k) {deque.addLast(cur.val);} else if (Math.abs(cur.val - target) < Math.abs(deque.peekFirst() - target)) {deque.pollFirst();deque.addLast(cur.val);}cur = cur.right;}List<Integer> res = new ArrayList<>(deque);return res;}}

LeetCode 272 Closest Binary Tree Traversal II 解题思路相关推荐

  1. Binary Tree Level Order Traversal II 解题思路

    思路: 与Binary Tree Level Order Traversal I 几乎一样.只是最后将结果存放在栈里,然后在栈里再传给向量即可. 再次总结思路: 两个queue,先把第一个放进q1,循 ...

  2. Leetcode 107. 二叉树的层次遍历 II 解题思路及C++实现

    解题思路: 使用队列实现二叉树的层序遍历,因为题目中要求每一层的val存储在一个vector中,所以在内循环中,还需要一个队列,用以存储更新每一层的节点. 在最后,需要将得到的res数组逆序. /** ...

  3. LeetCode 中等难度 92. 反转链表 II解题思路

    92. 反转链表 II 题目:中等难度 反转从位置 m 到 n 的链表.请使用一趟扫描完成反转. 说明: 1 ≤ m ≤ n ≤ 链表长度. 示例: 输入: 1->2->3->4-& ...

  4. Leetcode 122. 买卖股票的最佳时机 II 解题思路及C++实现

    解题思路: 采用贪心策略,只要后一天的价格高于前一天,就将差价加进来.得到的结果就是能获取的最大利润. class Solution { public:int maxProfit(vector< ...

  5. LeetCode: 106. Construct Binary Tree from Inorder and Postorder Traversal

    题目 Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume ...

  6. LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal 由前序和中序遍历建立二叉树 C++...

    LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal 由前序和中序遍历建立二叉树 C++ Given preo ...

  7. LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal

    LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal Solution1:我的答案 仿照105题写的答案 / ...

  8. LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal

    LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal 本博客转载自:http://www.cnblogs.co ...

  9. leetcode 971. Flip Binary Tree To Match Preorder Traversal

    leetcode 971. Flip Binary Tree To Match Preorder Traversal 题意:给一颗二叉树,再给一个的数组,能否通过交换两个左右两个子节点,使得二叉树的前 ...

最新文章

  1. 操作-《oracle入门到精通》第六章开始
  2. python菜鸟excel教程-Python菜鸟之路: 封装通用excel操作
  3. AI:2020年6月23日北京智源大会顶级大佬邝子平、李开复 、陆奇、张亚勤、曹勖文进行云上圆桌论坛《探讨AI与创业》
  4. Map与object的区别
  5. ios UITableView默认选中第一行
  6. java cassandra连接池_java操作cassandra(连接池)
  7. 互联网巨头曾经碾压了线下实体经济
  8. BZOJ2160 拉拉队排练【Manacher】
  9. 如何直观的长时间统计Android应用的动态内存消耗
  10. 管理感悟:下结论的套路
  11. springboot的异常处理
  12. 【Json工具类】json数据格式转换
  13. AVAudioPlayer音频播放器—IOS开发
  14. 网络邻居无法查找计算机,局域网中无法找到网上邻居的原因
  15. vscode 之 code lens
  16. IIS如何添加MIME类型.svg/.woff2/.woff
  17. 不属于计算机系统的输出设备,不是电脑的输出设备的是什么
  18. php语法变化大,浅析PHP7新功能及语法变化总结
  19. JavaScript 基础(002_Event Bubbling)
  20. 从零开始之uboot、移植uboot2017.01(五、board_init_f分析)

热门文章

  1. html5 java 实现 微信获取认证身份信息
  2. python对seo有什么用_python对于做SEO主要有什么作用-乐云SEO
  3. 蓝桥真题:迷宫(2017年省赛)
  4. QT添加lib库后提示 No rule to make target “xxx.lib“ needed by “xxx.exe“
  5. 【Linux】循序渐进学运维-服务篇-rsync实战
  6. 【DevOps】持续集成环境-Jenkins安装图文版
  7. 欧盟gmp中的计算机系统验证,欧盟GMP中的计算机系统验证.doc
  8. appcan案例书目录
  9. 求拉格朗日多项式matlab,拉格朗日插值多项式积分求圆周率近似Matlab实现
  10. mysql中int最大多少,MySQL中int最大值深入讲解