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?

查找二叉搜索树中第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) {
        int count = 0, res = 0;
        helper(root, k, res);
        return res;
    }
    
    void helper(TreeNode* node, int &k, int &res)
    {
        if (node->left != NULL)
            helper(node->left, k, res);
        k--;
        if (k == 0) {
            res = node->val;
            return;
        }
        if (node->right != NULL)
            helper(node->right, k, res);
    }
};

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