Skip to content

Commit d4c79cc

Browse files
authored
Create yeongu.cpp
1 parent 6c4376e commit d4c79cc

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
TC: O(n log n) 왜냐하면, heap에 push연산이 log n이고 각 노드마다 실행하므로.
2+
SC: O(n) queue가 n까지 커질수 있음.
3+
4+
int kthSmallest(TreeNode* root, int k) {
5+
priority_queue<int, vector<int>, greater<int>> minHeap;
6+
7+
// bfs
8+
queue<TreeNode*> q;
9+
if (root != nullptr) {
10+
q.push(root);
11+
};
12+
while (!q.empty()) {
13+
minHeap.push(q.front()->val);
14+
if (q.front()->left != nullptr) {
15+
q.push(q.front()->left);
16+
}
17+
if (q.front()->right != nullptr) {
18+
q.push(q.front()->right);
19+
}
20+
q.pop();
21+
}
22+
23+
for (int i = 0; i < k - 1; i++) {
24+
minHeap.pop();
25+
}
26+
return minHeap.top();
27+
}

0 commit comments

Comments
 (0)