230. Kth Smallest Element in a BST 找到bst中的第k小的元素

[抄题]:

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.

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  / 
 1   4
  
   2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / 
     3   6
    / 
   2   4
  /
 1
Output: 3

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

第1小的元素index为0,以此类推,第k小的元素index为k-1

[思维问题]:

知道是写in-order,但是不太记得要加if条件了

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

就是写个in-order,然后get第 k-1个就行了

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

traversal就是要加if

public void inOrderTraversal(List<Integer> result, TreeNode root) {
        //Traversal
        if (root.left != null) inOrderTraversal(result, root.left);
        result.add(root.val);
        if (root.right != null) inOrderTraversal(result, root.right);
    }

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

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?

可以变化节点:添加一个traverse的build

第k大不停变化:每个点添加一个总数count标记,然后

if (rootWithCount.left.count == k-1) return rootWithCount.val;

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        //initialization
        List<Integer> result = new ArrayList<Integer>();
        
        //Traversal
        inOrderTraversal(result, root);
        
        //return
        return result.get(k - 1);
    }
    
    public void inOrderTraversal(List<Integer> result, TreeNode root) {
        //Traversal
        if (root.left != null) inOrderTraversal(result, root.left);
        result.add(root.val);
        if (root.right != null) inOrderTraversal(result, root.right);
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/9412671.html