0% found this document useful (0 votes)
2 views

C++ CODE

The document contains C++ code for a binary tree implementation with a breadth-first search (BFS) function. The TreeNode class defines the structure of each tree node, and the bfs function traverses the tree level by level, printing the values of the nodes at each level. The BFS starts from the root and uses a queue to manage the nodes to be processed.

Uploaded by

dekic66784
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C++ CODE

The document contains C++ code for a binary tree implementation with a breadth-first search (BFS) function. The TreeNode class defines the structure of each tree node, and the bfs function traverses the tree level by level, printing the values of the nodes at each level. The BFS starts from the root and uses a queue to manage the nodes to be processed.

Uploaded by

dekic66784
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <iostream>

#include <queue>

using std::cout;
using std::endl;
using std::queue;

class TreeNode {
public:
int val_;
TreeNode* left = nullptr;
TreeNode* right = nullptr;

TreeNode(int val) {
val_ = val;
}
};

void bfs(TreeNode* root) {


queue<TreeNode*> queue;

if (root) {
queue.push(root);
}

int level = 0;
while (queue.size() > 0) {
cout << "level: " << level << endl;
int length = queue.size();
for (int i = 0; i < length; i++) {
TreeNode* curr = queue.front();
queue.pop();
cout << curr->val_ << ' ';
if (curr->left) {
queue.push(curr->left);
}
if (curr->right) {
queue.push(curr->right);
}
}
level++;
cout << endl;
}
}

You might also like