-
Notifications
You must be signed in to change notification settings - Fork 288
/
AC_bfs_n.cpp
61 lines (52 loc) · 1.31 KB
/
AC_bfs_n.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
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_bfs_n.cpp
* Create Date: 2014-12-22 09:06:27
* Descripton: bfs, use the seperator in queue
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
// 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) {
queue<TreeNode *> q;
vector<vector<int> > res;
vector<int> tmpv;
TreeNode *front;
if (root == NULL)
return res;
// bfs
q.push(root);
q.push(NULL); // NULL is the seperator of levels
while (!q.empty()) {
front = q.front();
q.pop();
if (front) {
tmpv.push_back(front->val);
if (front->left)
q.push(front->left);
if (front->right)
q.push(front->right);
} else if (!tmpv.empty()) {
res.push_back(tmpv);
tmpv.clear();
q.push(NULL);
}
}
return res;
}
};
int main() {
TreeNode *p = new TreeNode(1);
Solution s;
s.levelOrder(p);
return 0;
}