File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ // TC: O(N)
2+ // SC: O(N)
3+
4+ /**
5+ * Definition for a binary tree node.
6+ * function TreeNode(val, left, right) {
7+ * this.val = (val===undefined ? 0 : val)
8+ * this.left = (left===undefined ? null : left)
9+ * this.right = (right===undefined ? null : right)
10+ * }
11+ */
12+ /**
13+ * @param {TreeNode } root
14+ * @param {number } k
15+ * @return {number }
16+ */
17+ var kthSmallest = function ( root , k ) {
18+ let result = null ;
19+
20+ dfs ( root ) ;
21+
22+ return result ;
23+
24+ function dfs ( current ) {
25+ if ( result !== null ) {
26+ return ;
27+ }
28+ if ( ! current ) {
29+ return ;
30+ }
31+
32+ dfs ( current . left ) ;
33+ if ( current . val >= 0 ) {
34+ if ( k === 1 ) {
35+ result = current . val ;
36+ }
37+ k -= 1 ;
38+ }
39+ dfs ( current . right ) ;
40+ }
41+ } ;
You can’t perform that action at this time.
0 commit comments