BUPT-homework/semester3/exercises/4-Trees/exercise4.35.cpp

39 lines
622 B
C++
Raw Normal View History

#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;
}