zoukankan      html  css  js  c++  java
  • 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?

    /**
     * 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:
        void _get_in_order_list(TreeNode* root, vector<int> &in_list) {
            if (NULL == root) {
                return;
            }
            _get_in_order_list(root->left, in_list);
            in_list.push_back(root->val);
            _get_in_order_list(root->right, in_list);
        }
        
        int kthSmallest(TreeNode* root, int k) {
            vector<int> in_list;
            _get_in_order_list(root, in_list);
            return in_list[k - 1];
        }
    };
  • 相关阅读:
    创建数据库链
    redis命令
    redis.conf文件配置信息
    mybatis调用存储过程实现
    oracle游标使用遍历3种方法
    Proud Merchants
    Bag Problem
    Watch The Movie
    Accepted Necklace
    Bone Collector II
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5215278.html
Copyright © 2011-2022 走看看