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

    本题开始做的时候想到了还是用前序遍历的方法来做,但是对于follow up就做不出来了,看了答案才发现,可以把二分搜索树分成三部分,一部分是二分搜索树的左子树,一部分是当前节点,一部分是二分搜索树的右子树部分。只要数出左子树的个数就可以找到第k小的元素了,代码如下:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int kthSmallest(TreeNode root, int k) {
    12         int count = countNodes(root.left);
    13         if(k<=count) return kthSmallest(root.left,k);
    14         else if(k>count+1) return kthSmallest(root.right,k-count-1);
    15         return root.val;
    16     }
    17     public int countNodes(TreeNode node){
    18         if(node==null) return 0;
    19         return 1+countNodes(node.left)+countNodes(node.right);
    20     }
    21 }
  • 相关阅读:
    asp.net的Context.Cache缓存过期策略
    sql语句执行时算术运算导致溢出。
    sqlserver进行join的方式选择
    Apollo配置中心
    sqlserver的left join优化
    iis设置上传文件大小限制
    Android中的颜色值
    Network authentication method and device for implementing the same
    MongoDB GridFS
    MongoDB 正则表达式
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6608196.html
Copyright © 2011-2022 走看看