The Problem: print all nodes of a binary tree in breadth first order.
A binary tree can be visualized like this:
+ A (root)
/ \
B (left) C (right child)
/ \ / \
D E F G
/ \
I J
The breadth first order traversal should be like: A B C D E F G I J.
The following program will use a queue to store necessary information for traversal in breath first order.
#include <iostream>
#include <queue>
using namespace std;
struct bnode {
int val;
bnode *_lchild;
bnode *_rchild;
bnode(int v=0, bnode *p=0, bnode *q=0)
:val(v),_lchild(p),_rchild(q){}
};
void breadth_first_traversal(bnode *root)
{
queue<bnode *> buf_ptrs;
if (root)
buf_ptrs.push(root);
while (buf_ptrs.size())
{
bnode *front = buf_ptrs.front();
cout<< front->val << endl; //print
if (front->_lchild)
buf_ptrs.push(front->_lchild);
if (front->_rchild)
buf_ptrs.push(front->_rchild);
buf_ptrs.pop();
}
}