首页 > 其他 > 详细

Kth Smallest Element in a BST

时间:2016-02-24 22:49:51      阅读:282      评论:0      收藏:0      [点我收藏+]

 

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST‘s total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

 

/**
 * 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 _get_in_order_list(TreeNode* root, vector<int> &in_list) {
        if (NULL == root) {
            return;
        }
        _get_in_order_list(root->left, in_list);
        in_list.push_back(root->val);
        _get_in_order_list(root->right, in_list);
    }
    
    int kthSmallest(TreeNode* root, int k) {
        vector<int> in_list;
        _get_in_order_list(root, in_list);
        return in_list[k - 1];
    }
};

 

Kth Smallest Element in a BST

原文:http://www.cnblogs.com/SpeakSoftlyLove/p/5215278.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!