[LeetCode] Closest Binary Search Tree Value II

简介: Problem Description: Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.

Problem Description:

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:

  1. 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.
  2. Try to assume that each node has a parent pointer, it makes the problem much easier.
  3. Without parent pointer we just need to keep track of the path from the root to the current node using a stack.
  4. You would need two stacks to track the path in finding predecessor and successor node separately.

There is a very simple idea to keep a max heap of size k and elements in the heap are sorted by their absolute difference from target. For the max heap, we will simply use the default priority_queue. Then we simply traverse the tree and push all its nodes to the heap while maintaining the size of heap not larger than k.

The code is as follows.

 1 class Solution {
 2 public:
 3     vector<int> closestKValues(TreeNode* root, double target, int k) {
 4         priority_queue<pair<double, int>> pq;
 5         closestK(root, pq, target, k);
 6         vector<int> closest;
 7         while (!pq.empty())
 8             closest.push_back(pq.top().second), pq.pop();
 9         return closest;
10     }
11 private:
12     void closestK(TreeNode* node, priority_queue<pair<double, int>>& pq, double target, int k) {
13         if (!node) return;
14         pq.push(make_pair(abs(target - node -> val), node -> val));
15         if (pq.size() > k) pq.pop();
16         closestK(node -> left, pq, target, k);
17         closestK(node -> right, pq, target, k);
18     }
19 };

Well, the hints of the problem suggest a solution using two stacks to track the predecessors and successors. This post has shared a nice implementation of it. The code is rewritten in C++ as follows.

 1 class Solution {
 2 public:
 3     vector<int> closestKValues(TreeNode* root, double target, int k) {
 4         vector<int> closest(k);
 5         stack<int> pre, suc;
 6         inorder(root, target, false, pre);
 7         inorder(root, target, true, suc);
 8         for (int i = 0; i < k; i++) {
 9             if (pre.empty()) closest[i] = suc.top(), suc.pop();
10             else if (suc.empty()) closest[i] = pre.top(), pre.pop();
11             else if (abs(target - pre.top()) < abs(target - suc.top()))
12                 closest[i] = pre.top(), pre.pop();
13             else closest[i] = suc.top(), suc.pop();
14         }
15         return closest;
16     }
17 private:
18     void inorder(TreeNode* root, double target, bool reversed, stack<int>& s) {
19         if (!root) return;
20         inorder(reversed ? root -> right : root -> left, target, reversed, s);
21         if ((reversed && root -> val <= target) || (!reversed && root -> val > target)) return;
22         s.push(root -> val);
23         inorder(reversed ? root -> left : root -> right, target, reversed, s);
24     }
25 };

 

目录
相关文章
|
5月前
Leetcode 74. Search a 2D Matrix
这道题很简单,为此专门写篇博客其实算博客凑数了。给你一个每一行每一列都是增序,且每一行第一个数都大于上一行末尾数的矩阵,让你判断某个数在这个矩阵中是否存在。 假设矩阵是m*n,扫一遍的时间复杂度就是O(m*n),题目中给出的这么特殊的矩阵,时间复杂度可以降到O(m+n),具体代码如下,写的比较挫。
62 1
|
5月前
Leetcode Minimum Depth of Binary Tree (面试题推荐)
计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。 我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。
24 0
|
5月前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
根据LCA的定义,二叉树中最小公共祖先就是两个节点p和q最近的共同祖先节点,LCA的定义没什么好解释的,主要是这道题的解法。
16 0
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree
|
27天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
1月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3

热门文章

最新文章