같은 레벨의 노드끼리 배열을 만들어 return한다.
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its level order traversal as:
[ [3], [9,20], [15,7] ]
풀이
- 큐와 bfs를 이용하여 레벨 별로 노드를 저장한다.
/**
* 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) {}
* };
*/
class Solution {
public:
void Traverse(TreeNode* root, vector<vector<int>> &answer){
queue<pair<TreeNode*, int>> q;
q.push(make_pair(root, 0));
while(!q.empty()){
TreeNode* cur = q.front().first;
int level = q.front().second;
q.pop();
if(cur != nullptr){
if(answer.size() < level+1){
vector<int> v = {cur->val};
answer.push_back(v);
}else {
answer[level].push_back(cur->val);
}
q.push(make_pair(cur->left, level+1));
q.push(make_pair(cur->right, level+1));
}
}
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> answer;
Traverse(root, answer);
return answer;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 98] Validate Binary Search Tree (0) | 2020.10.04 |
---|---|
[leetcode 94] Binary Tree Inorder Traversal (0) | 2020.10.04 |
[leetcode 993] Cousins in Binary Tree (0) | 2020.10.03 |
[leetcode 1022] Sum of Root To Leaf Binary Numbers (0) | 2020.10.03 |
[leetcode 560] Subarray Sum Equals K (0) | 2020.10.01 |
댓글