We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 99e625f commit a7ba2d0Copy full SHA for a7ba2d0
solution/src/main/java/com/inuker/solution/KthSmallestElementInBST.java
@@ -8,6 +8,17 @@
8
* Created by dingjikerbo on 16/11/30.
9
*/
10
11
+/**
12
+ * 这题关键是follow up
13
+ * 如果更新频繁,则通常的做法每次都是O(n),更优的做法是O(lgn)
14
+ * 即给node中记录左子树的节点个数,这样在找kth smallest时流程如下:
15
+ * 假设root的左子树节点有N个,则
16
+ * 1, 当K=N+1时,kth就是root
17
+ * 2, 当K<N+1时,kth就到左子树中找
18
+ * 3, 当K>N+1时,就到右子树中找第K-N-1个
19
+ * 所以当给定一棵树时,我们要先重建一下这棵树,统计一下各节点的左子树节点数,虽然首次是O(n)
20
+ * 但是之后就是O(h)了。
21
+ */
22
public class KthSmallestElementInBST {
23
24
public int kthSmallest(TreeNode root, int k) {
0 commit comments