Skip to content

Commit a7ba2d0

Browse files
author
liwentian
committed
fd
1 parent 99e625f commit a7ba2d0

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

solution/src/main/java/com/inuker/solution/KthSmallestElementInBST.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,17 @@
88
* Created by dingjikerbo on 16/11/30.
99
*/
1010

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+
*/
1122
public class KthSmallestElementInBST {
1223

1324
public int kthSmallest(TreeNode root, int k) {

0 commit comments

Comments
 (0)