-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Level Order Traversal.txt
82 lines (81 loc) · 2.29 KB
/
Binary Tree Level Order Traversal.txt
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
/**
* Definition for binary tree
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> rets;
if (root == NULL)
return rets;
list<TreeNode*>* inner = new list<TreeNode*>;
list<TreeNode*>* outer;
inner->push_back(root);
while(!inner->empty()) {
outer = new list<TreeNode*>;
rets.push_back(vector<int>(0));
while(!inner->empty()) {
TreeNode* node = inner->front();
inner->pop_front();
rets.back().push_back(node->val);
if (node->left)
outer->push_back(node->left);
if (node->right)
outer->push_back(node->right);
}
delete inner;
inner = outer;
}
delete inner;
return rets;
}
};
/**
* Definition for binary tree
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> rets(1, vector<int>(0));
if (root) {
list<TreeNode*> queue;
queue.push_back(root);
int p = 0, ob = 0, nb = 0;
while (!queue.empty()) {
TreeNode* node = queue.front();
queue.pop_front();
rets.back().push_back(node->val);
if (node->left) {
queue.push_back(node->left);
nb++;
}
if (node->right) {
queue.push_back(node->right);
nb++;
}
if (p == ob) {
rets.push_back(vector<int>(0));
ob = nb;
}
p++;
}
}
rets.pop_back();
return rets;
}
};