leetcode No230. Kth Smallest Element in a BST

Question:

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?

Algorithm:

如果按照中序遍历的顺序遍历一颗BST,遍历序列的数值是递增排序的。

Accepted Code:

/**
 * 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) {
        return helper(root,k);
    }
    int helper(TreeNode* root, int &k){
        if(root==NULL)
            return -1;
        if(root->left){
            int temp=helper(root->left,k);
            if(temp!=-1)
                return temp;
        }
        if(k==1)
            return root->val;
        k--;
        return helper(root->right,k);
    }
};


你可能感兴趣的:(LeetCode)