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

[抄題]:node

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:ide

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

 [暴力解法]:ui

時間分析:spa

空間分析:debug

 [優化後]:3d

時間分析:code

空間分析:

[奇葩輸出條件]:

[奇葩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
相關文章
相關標籤/搜索