forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0103.cpp
37 lines (32 loc) · 1.09 KB
/
0103.cpp
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
32
33
34
35
36
37
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
if (root == nullptr) {
return result;
}
stack<TreeNode*> currentLevel;
stack<TreeNode*> nextLevel;
bool leftToRight = true;
currentLevel.push(root);
while (!currentLevel.empty()) {
vector<int> levelValues;
while (!currentLevel.empty()) {
TreeNode* node = currentLevel.top();
currentLevel.pop();
levelValues.push_back(node->val);
if (leftToRight) {
if (node->left) nextLevel.push(node->left);
if (node->right) nextLevel.push(node->right);
} else {
if (node->right) nextLevel.push(node->right);
if (node->left) nextLevel.push(node->left);
}
}
result.push_back(levelValues);
swap(currentLevel, nextLevel);
leftToRight = !leftToRight;
}
return result;
}
};