File tree 2 files changed +56
-0
lines changed
2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 83
83
| 222| [ 完全二叉树的节点个数] ( https://leetcode.cn/problems/count-complete-tree-nodes/ ) | [ JavaScript] ( ./algorithms/count-complete-tree-nodes.js ) | Medium|
84
84
| 225| [ 用队列实现栈] ( https://leetcode.cn/problems/implement-stack-using-queues/ ) | [ JavaScript] ( ./algorithms/implement-stack-using-queues.js ) | Easy|
85
85
| 226| [ 翻转二叉树] ( https://leetcode.cn/problems/invert-binary-tree/ ) | [ JavaScript] ( ./algorithms/invert-binary-tree.js ) | Easy|
86
+ | 230| [ 二叉搜索树中第K小的元素] ( https://leetcode.cn/problems/kth-smallest-element-in-a-bst/ ) | [ JavaScript] ( ./algorithms/kth-smallest-element-in-a-bst.js ) | Medium|
86
87
| 231| [ 2 的幂] ( https://leetcode.cn/problems/power-of-two/ ) | [ JavaScript] ( ./algorithms/power-of-two.js ) | Easy|
87
88
| 232| [ 用栈实现队列] ( https://leetcode.cn/problems/implement-queue-using-stacks/ ) | [ JavaScript] ( ./algorithms/implement-queue-using-stacks.js ) | Easy|
88
89
| 234| [ 回文链表] ( https://leetcode-cn.com/problems/palindrome-linked-list/ ) | [ JavaScript] ( ./algorithms/palindrome-linked-list.js ) | Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val, left, right) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.left = (left===undefined ? null : left)
6
+ * this.right = (right===undefined ? null : right)
7
+ * }
8
+ */
9
+ /**
10
+ * @param {TreeNode } root
11
+ * @param {number } k
12
+ * @return {number }
13
+ */
14
+ var kthSmallest = function ( root , k ) {
15
+ // 中序遍历二叉搜索树相当与遍历有序数组
16
+
17
+ // 递归 需要遍历整棵树
18
+ let counter = 0 ;
19
+ let rankKNum = 0 ;
20
+ const dfs = ( root ) => {
21
+ if ( ! root ) return null ;
22
+ dfs ( root . left ) ;
23
+ counter ++ ;
24
+ if ( k === counter ) {
25
+ rankKNum = root . val ;
26
+ }
27
+ dfs ( root . right ) ;
28
+ } ;
29
+ dfs ( root ) ;
30
+ return rankKNum ;
31
+
32
+ // 迭代 无需遍历整棵树
33
+ // return inOrderIterate(root, k);
34
+ } ;
35
+
36
+ function inOrderIterate ( root , k ) {
37
+ const stack = [ ] ;
38
+ let curr = root ,
39
+ node = null ;
40
+ while ( stack . length || curr ) {
41
+ while ( curr ) {
42
+ stack . push ( curr ) ;
43
+ curr = curr . left ;
44
+ }
45
+ node = stack . pop ( ) ;
46
+ k -- ;
47
+ if ( k === 0 ) {
48
+ break ;
49
+ }
50
+ if ( node . right ) {
51
+ curr = node . right ;
52
+ }
53
+ }
54
+ return node . val ;
55
+ }
You can’t perform that action at this time.
0 commit comments