• Leetcode 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?

    Hint:

      1. Try to utilize the property of a BST.
      2. What if you could modify the BST node's structure?
      3. The optimal runtime complexity is O(height of BST).

    题目意思:

      给定一棵二叉搜索树,找到第k小的元素

      注意:

        1、利用二叉搜索树的特性

        2、修改二叉搜索树的节点结构

        3、最优时间复杂度是0(树的高度)

    解题思路:

    方法一:

      二叉搜索树的特性:其中序遍历是有序的。故中序遍历访问,访问第k个元素即可。

                               

    方法二:

      利用分冶的方法。

    • 统计根节点左子树的节点个数cnt
    • 如果cnt+1 = k,则根节点即为第k个最小元素
    • 如果cnt+1 > k,则第k个最小元素在左子树,root = root->left;
    • 如果cnt+1 < k,则第k个最小元素在右子树,root = root->right;
    • 重复第一步

    源代码:

    方法一:

     1 class Solution {
     2 public:
     3     int kthSmallest(TreeNode* root, int k) {
     4         stack<TreeNode*> nodeStack;
     5         if(root == NULL) return -1;
     6         while(true){
     7             while(root){
     8                 nodeStack.push(root);
     9                 root = root->left;
    10             }
    11             TreeNode* node = nodeStack.top(); nodeStack.pop();
    12             if(k == 1) return node->val;
    13             else root = node->right,k--;
    14         }
    15     }
    16 };

    方法二:

     1 class Solution {
     2 public:
     3     int calcNodeSize(TreeNode* root){
     4         if( root == NULL) return 0;
     5         return 1 + calcNodeSize(root->left) + calcNodeSize(root->right);
     6     }
     7     
     8     int kthSmallest(TreeNode* root, int k) {
     9         if(root == NULL) return 0;
    10         int cnt = calcNodeSize(root->left);
    11         if(k == cnt + 1) return root->val;
    12         else if( k < cnt + 1 ) return kthSmallest(root->left,k);
    13         else return kthSmallest(root->right, k-cnt-1);
    14     }
    15 };

      

  • 相关阅读:
    (0.12)elasticsearch分布式集群原理(ES7.9)
    (0.9)elasticsearch分布式集群概念
    mysql分库分表【转】
    (0.11)elasticsearch常用查询,REST API的基本约定,ES增删查改
    mysql全日志自动化脚本
    Java虚拟机--类加载的过程
    Java虚拟机--运行时数据区域
    新题型|结构不良题
    恒等变形的是与非
    分形图与二阶数列
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/4628357.html
Copyright © 2020-2023  润新知