[leetcode] 272. Closest Binary Search Tree Value II 解题报告

题目链接:https://leetcode.com/problems/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 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:
    1. getPredecessor(N), which returns the next smaller node to N.
    2. 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.

思路: 利用二叉搜索树的中序遍历, 如果结果集合中元素还不到k个, 就把当前元素加到集合中去, 如果集合中的元素个数多于k了, 那么有二种情况:

1. target的值比集合中最小的值小, 因为中序遍历是有序的, 最小元素就是第0个元素

2. target的值大于结果集合中的最小值, 小于最大值

3. target的值大于集合中的最大值

当集合中的元素个数大于k的时候, 我们需要进行元素替换. 

如果是第一种情况, 那么将无法进行替换, 因为第0个元素就是最靠近的值, 并且在集合中元素是有序的, 因此此时集合中就是最靠近的k个元素.

如果是第二三种情况, 那么我们比较当前值和集合中最小值, 如果当前结点值比那个值更靠近target, 那么我们就用当前元素替换最小的值

直到我们无法再找到能够替换的元素, 就可以返回结果了.

时间复杂度O(N)

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> closestKValues(TreeNode* root, double target, int k) {
        if(!root) return result;
        closestKValues(root->left, target, k);
        if(result.size() < k) result.push_back(root->val);
        else if(fabs(target-result[index]) > fabs(target-root->val))
        {
            result[index++] = root->val;
            if(index==k) index = 0;
        }
        else return result;
        closestKValues(root->right, target, k);
        return result;
    }
private:
    vector<int> result;
    int index = 0;
};

参考: https://leetcode.com/discuss/83431/c-simple-inorder-solution-with-o-n-runtime-and-o-k-memory


还有一种O(logn)的方法, 利用两个栈来保存target的前驱和后继, 而且栈顶的元素保存的是距离target最近的前驱和后继, 这样就可以每次取到距离target最近的值. 这种时间复杂度可以达到O(logn).

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void initStack(TreeNode* root, double target)
    {
        while(root)
        {
            if(root->val <= target) 
            {
                pre.push(root);
                root = root->right;
            }
            else 
            {
                succ.push(root);
                root = root->left;
            }
        }
    }
    
    void getPre()
    {
        auto node = pre.top();
        pre.pop();
        if(node->left)
        {
            pre.push(node = node->left);
            while(node->right)
                pre.push(node = node->right);
        }
    }
    
    void getSucc()
    {
        auto node = succ.top();
        succ.pop();
        if(node->right)
        {
            succ.push(node = node->right);
            while(node->left)
                succ.push(node = node->left);
        }
    }
    
    vector<int> closestKValues(TreeNode* root, double target, int k) {
        if(!root) return {};
        initStack(root, target);
        while(k-- > 0)
        {
            if(pre.empty()||(!succ.empty() && fabs(pre.top()->val-target) > fabs(succ.top()->val-target)))
            {
                ans.push_back(succ.top()->val);
                getSucc();
            }
            else
            {
                ans.push_back(pre.top()->val);
                getPre();
            }
        }
        return ans;
    }
private:
    stack<TreeNode*> pre, succ;
    vector<int> ans;
};















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值