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.

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?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?

  1. The optimal runtime complexity is O(height of BST).
【思路】二叉搜索树本身是有序的,中序遍历二叉搜索树,第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) {
        vector<int> tree;
        stack<TreeNode*> stk;
        TreeNode* tmp = root;
        while(!stk.empty()||tmp!=NULL)
        {
            while(tmp!=NULL)
            {
                stk.push(tmp);
                tmp = tmp->left;
            }
            tmp = stk.top();
            tree.push_back(tmp->val);
            stk.pop();
            tmp = tmp->right;
        }
        return tree[k-1];
    }
};


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