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);
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容