首页 > 其他 > 详细

Kth Smallest Element in a BST

时间:2015-07-12 17:26:21      阅读:217      评论:0      收藏:0      [点我收藏+]

该题的思路很简单,就是对BST进行先序遍历,找到第k个数的时候返回。这里借助栈用迭代实现,递归的代码更简单,没有尝试。

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode *> cache;
        TreeNode *point = root;
        TreeNode *tmp;
        int i = 0;
//先序遍历
        while(point || !cache.empty()){
            while(point){
                cache.push(point);
                point = point -> left;
            }
            if(!cache.empty()){
                tmp = cache.top();
                i++;
                if(i == k)
                    return tmp -> val;
                cache.pop();
                point = tmp -> right;
            }
        }
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

Kth Smallest Element in a BST

原文:http://blog.csdn.net/ny_mg/article/details/46851163

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