-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path102.binary-tree-level-order-traversal.cpp
84 lines (74 loc) · 1.91 KB
/
102.binary-tree-level-order-traversal.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
//Definition for a binary tree node.
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> levelOrder(TreeNode *root)
{
vector<vector<int>> result;
if (root == nullptr)
{
return result;
}
struct TreeNode *t = root;
queue<TreeNode *> q;
q.push(root);
int level = 0;
while (!q.empty())
{
vector<int> levelResult;
int levelLength = q.size();
while (levelLength-- > 0)
{
t = q.front();
levelResult.push_back(t->val);
q.pop();
if (t->left != nullptr)
{
q.push(t->left);
}
if (t->right != nullptr)
{
q.push(t->right);
}
}
level++;
result.push_back(levelResult);
}
return result;
}
};
int main(int argc, char const *argv[])
{
struct TreeNode *tree = new TreeNode(1);
struct TreeNode *treeLeft = new TreeNode(2);
struct TreeNode *treeRight = new TreeNode(3);
struct TreeNode *treeLeftLeft = new TreeNode(4);
struct TreeNode *treeRightRight = new TreeNode(5);
tree->left = treeLeft;
tree->right = treeRight;
treeLeft->left = treeLeftLeft;
treeRight->right = treeRightRight;
Solution solution;
vector<vector<int>> result = solution.levelOrder(tree);
for (auto it = result.begin(); it != result.end(); ++it)
{
vector<int> levelResult = *it;
for (auto jt = levelResult.begin(); jt != levelResult.end(); ++jt)
{
cout << *jt << " ";
}
cout << endl;
}
return 0;
}