Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- ebs
- github
- EC2
- intervals
- POD
- DevOps
- IAC
- K8S
- 자바스크립트
- AWS
- FastAPI
- elasticsearch
- asyncio
- EKS
- 쿠버네티스
- docker
- Deployment
- Kubernetes
- Python
- leetcode
- asgi
- event loop
- ansible
- Django
- dockerfile
- YAML
- terraform
- WSGI
- IAM
- Service
Archives
- Today
- Total
궁금한게 많은 개발자 노트
[ leetcode ] 102. Binary Tree Level Order Traversal 본문
Binary Tree가 주어졌을 때, level order로 순회하는 순서를 반환하는 문제입니다.
BFS(Breadth-First-Search)로 접근하여 최상위 노드부터 넣고 자식들을 순서대로 넣으면서 level order로 순회합니다.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include <algorithm>
#include <queue>
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (root) tree_queue.push(root);
vector<vector<int>> answer;
queue<TreeNode*> tree_queue;
while (!tree_queue.empty()) {
vector<int> level;
int size = tree_queue.size();
for (int i = 0; i < size; i++) {
TreeNode* current = tree_queue.front();
tree_queue.pop();
level.push_back(current->val);
if (current->left) tree_queue.push(current->left);
if (current->right) tree_queue.push(current->right);
}
answer.push_back(level);
}
return answer;
}
};
'Algorithm' 카테고리의 다른 글
[ leetcode ] 450. Delete Node in a BST (0) | 2023.05.02 |
---|---|
[ leetcode ] 11. Container With Most Water (0) | 2023.05.02 |
[ leetcode ] 110. Balanced Binary Tree (0) | 2023.05.02 |
[ leetcode ] 111. Minimum Depth of Binary Tree (0) | 2023.05.02 |
[ leetcode ] 258. Add Digits (0) | 2023.05.02 |
Comments