-
Notifications
You must be signed in to change notification settings - Fork 9
/
LevelOrderTraversal.cpp
56 lines (51 loc) · 1.45 KB
/
LevelOrderTraversal.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Problem-Link: https://leetcode.com/problems/binary-tree-level-order-traversal/
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
// 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 LevelOrderTraversal {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode*> q_odd;
queue<TreeNode*> q_even;
// Step-I: Initializing the Queue.
if (root) q_odd.push(root);
bool isOdd = true;
// Step-II: Go through both the queues and drain them.
while (q_odd.size() > 0 || q_even.size() > 0) {
vector<int> curr;
if (isOdd) {
// Drain the odd queue.
while (q_odd.size() > 0) {
TreeNode* tmp = q_odd.front(); q_odd.pop();
if (tmp->left) q_even.push(tmp->left);
if (tmp->right) q_even.push(tmp->right);
curr.push_back(tmp->val);
}
result.push_back(curr);
} else {
// Drain the even queue.
while (q_even.size() > 0) {
TreeNode* tmp = q_even.front(); q_even.pop();
if (tmp->left) q_odd.push(tmp->left);
if (tmp->right) q_odd.push(tmp->right);
curr.push_back(tmp->val);
}
result.push_back(curr);
}
// Flipping the bit.
isOdd = not isOdd;
}
return result;
}
};