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 a2ec0d6 commit 4d5a551Copy full SHA for 4d5a551
1 file changed
kth-smallest-element-in-a-bst/jdy8739.js
@@ -0,0 +1,37 @@
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
+ const arr = [];
16
+
17
+ const dfs = (node) => {
18
+ arr.push(node.val);
19
20
+ if (node?.left) {
21
+ dfs(node.left);
22
+ }
23
24
+ if (node?.right) {
25
+ dfs(node.right);
26
27
28
29
+ dfs(root);
30
31
+ const sort = arr.sort((a, b) => a - b);
32
33
+ return sort[k - 1];
34
+};
35
36
+// 시간복잡도 -> O(nlogn) dfs로 노드의 val을 배열에 넣고 정렬하는 시간이 소요됨
37
+// 공간복잡도 -> O(n) 리스트의 길이만큼 arr의 공간이 필요함
0 commit comments