Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its zigzag level order traversal as:
문제 풀이:
기존 level 순회에서 레벨에 따라 reverse가 추가된다.
/**
* 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:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
vector<int> tmp;
if(root == nullptr){
return result;
}
queue<TreeNode*> q;
q.push(root);
int level = -1;
while(!q.empty()){
level++;
int len = q.size();
for(int i=0; i<len; i++){
TreeNode* fr = q.front();
tmp.push_back(fr->val);
q.pop();
if(fr -> left){
q.push(fr -> left);
}
if(fr->right){
q.push(fr -> right);
}
}
if(level % 2 == 1){
reverse(tmp.begin(), tmp.end());
}
result.push_back(tmp);
tmp.clear();
}
return result;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 332] Reconstruct Itinerary (0) | 2023.04.15 |
---|---|
[leetcode 378] Kth Smallest Element in a Sorted Matrix (0) | 2021.02.11 |
[leetcode 268] Missing Number (0) | 2020.12.03 |
[leetcode 190] Reverse Bits (0) | 2020.12.03 |
[leetcode 242] Valid Anagram (0) | 2020.12.01 |
댓글