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