zoukankan      html  css  js  c++  java
  • LeetCode 230: Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find thekth 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个元素。

    算法如下:

    1、计算左子树元素个数left。

    2、 left+1 = K,则根节点即为第K个元素

          left >=k, 则第K个元素在左子树中,

         left +1 <k, 则转换为在右子树中,寻找第K-left-1元素。

    代码如下:

    /**
     * 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 calculateSize(TreeNode* root){
            if(root == NULL)
                return 0;
            return 1 + calculateSize(root->left) + calculateSize(root->right);
        }
        int kthSmallest(TreeNode* root, int k) {
            if (root == NULL)
                return 0;
            int leftSize = calculateSize(root->left);   //计算左子树的元素个数
            if(k == leftSize+1) // 如果k == 左子树 + 1,那么正好的根节点,因为二叉搜索树的左子树小于根,右子树大于根
                return root->val;
            else if(k <= leftSize)  //left >=k, 则第K个元素在左子树中
                return kthSmallest(root->left, k);
            else                    //eft +1 <k, 则转换为在右子树中,寻找第K-left-1元素。
                return kthSmallest(root->right, k-leftSize-1);
            
        }
    };
    

      

  • 相关阅读:
    DM数据库disql的使用 Disql disql 达梦数据库Disql
    移动端禁止蒙层下的页面滚动
    移动端如何自动适配px
    使用Vant做移动端对图片预览ImagePreview和List的理解
    uniapp中使用uView组件库
    h5使用vuephotopreview 做全屏预览
    jsonview的实现
    PC端自适应使用rem 移动端适配升级版
    axios解决跨域问题(vuecli3.0)
    vs code 配置git path
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6571991.html
Copyright © 2011-2022 走看看