39 lines
622 B
C++
39 lines
622 B
C++
|
#include <queue>
|
||
|
#include <cstdio>
|
||
|
|
||
|
typedef struct TreeNode {
|
||
|
struct TreeNode *l;
|
||
|
struct TreeNode *r;
|
||
|
int val;
|
||
|
} TreeNode;
|
||
|
|
||
|
// answer begins here
|
||
|
void BFS(TreeNode *node) {
|
||
|
std::queue<TreeNode *> todo;
|
||
|
if (node) {
|
||
|
todo.push(node);
|
||
|
}
|
||
|
|
||
|
while (!todo.empty()) {
|
||
|
for (int i = 0, size = todo.size(); i < size; i++) {
|
||
|
auto ptr = todo.front();
|
||
|
std::printf("%d ", ptr->val);
|
||
|
todo.pop();
|
||
|
|
||
|
if (ptr->l) {
|
||
|
todo.push(ptr->l);
|
||
|
}
|
||
|
if (ptr->r) {
|
||
|
todo.push(ptr->r);
|
||
|
}
|
||
|
}
|
||
|
printf("\n");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// answer ends
|
||
|
int main(void) {
|
||
|
BFS(nullptr);
|
||
|
return 0;
|
||
|
}
|