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

      

  • 相关阅读:
    自定义类型百度地图之自定义地图类型详解
    电话文本android(3)_拨打电话操作
    检查运行IIS 5.1 使用出现server application error解决方法
    function运行令人吐血的IE JS兼容性问题。。。
    组件设置window2008 64位系统无法调用Microsoft.Office.Interop组件进行文件另存的解决办法
    api时间转换VarDateFromStr,VariantTimeToSystemTime
    C与CPP文件的区别
    OpenSSL 使用指南
    Pascal保留字/关键字列表
    windbg 启动参数,常用命令
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/4628357.html
Copyright © 2020-2023  润新知