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.

 

cpp:

方法一:递归

class Solution {
public:
    int kthSmallest(TreeNode* root,int k){
        int result;
        inOrder(root,k,result);
        return result;
    }

    int n =0;
    void inOrder(TreeNode* root,int kth,int& kthVal){
        if(!root ) return;
        inOrder(root->left,kth,kthVal);
        n = n + 1;
        if(n == kth) {
            kthVal = root->val;
            return;
        }
        inOrder(root->right,kth,kthVal);
    }

};

方法2:栈

class Solution{
public:
    int kthSmallest(TreeNode* root,int k){
        stack<TreeNode*> stack;
        int result;
        TreeNode *cur = root;
        while(!stack.empty() || cur){
            if(cur){
                stack.push(cur);
                cur = cur->left;
            }else{
                TreeNode* temp = stack.top();
                stack.pop();
                k--;
                if(k==0) {
                    result = temp->val;
                    return result;
                }
                cur = temp->right;
            }
        }

        return result;
    }


};

 

你可能感兴趣的:(Kth Smallest Element in a BST)