[抄题]: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); } }