230. Kth Smallest Element in a BST

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.

//二叉搜索树倒数第k个元素 中序遍历即可

/**
 * 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:
    int kthSmallest(TreeNode* root, int k) {
        if(!root|| k<=0)   return 0;
        
        stack<TreeNode*> s;
        TreeNode*p = root;
        while(p || !s.empty()){
            if(p){
                s.push(p);
                p = p->left;
            }
            else{
                p = s.top();
                if(--k == 0)
                    return p->val;
                s.pop();
                p = p->right;
            }
        }
        
        return 0;
    }
};

 

posted on 2017-03-06 09:36  123_123  阅读(71)  评论(0编辑  收藏  举报