leetcode 230二叉搜索树中第k小的元素

通过stack进行中序遍历迭代,timeO(k),spaceO(1)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/**
BST中序遍历是从小到大排列的因此对其进行中序遍历然后取第k个元素;
**/
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        if(root==NULL) return 0;
        int res=0,i=1;
        stack<TreeNode*> s;
        TreeNode* p=root;
        s.push(root);
        while(!s.empty()){
            while(p&&p->left){
                p=p->left;s.push(p);
            }
            p=s.top();s.pop();
            if(i==k) {res=p->val;break;}
            i++;
            
            p=p->right;
            if(p) s.push(p);
        }
        return res;
    }
};

改进的话则建立一个private vector<int> arr,当k<arr.size()的时候第k大的元素已经存在,当k>arr.size()时不存在,需要继续执行搜索;或者先全部遍历一遍存储到arr中,然后再查找;

原文地址:https://www.cnblogs.com/joelwang/p/10919603.html