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);
            
        }
    };
    

      

  • 相关阅读:
    MVC ORM 架构
    Kubernetes 第八章 Pod 控制器
    Kubernetes 第七章 Configure Liveness and Readiness Probes
    Kubernetes 第六章 pod 资源对象
    Kubernetes 第五章 YAML
    Kubernetes 核心组件
    Kubernetes 架构原理
    Kubernetes 第四章 kubectl
    Kubernetes 第三章 kubeadm
    yum 配置及yum 源配置
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6571991.html
Copyright © 2011-2022 走看看