osjunkie
BAN USER// C++ Print levels
// Variable count tracks the number of nodes at a specific level.
// We know that first level has count '1'
// We first process nodes at the level, and enqueue its children in
// the queue.
// Once we have processed all nodes at a specific level
// (as indicated by count == 0),
// the queue then has nodes that belong to the next level
class node {
public:
node *l, *r;
int v;
};
void levels(node * n) {
queue<node *> q;
q.enqueue(n);
int count = 1; // Queue has one node at this level
while(!q.empty()) {
node * n1 = q.top();
cout << n1->v << " ";
if (n1->l) {
q.enqueue(n1->l);
}
if (n1->r) {
q.enqueue(n1->r);
}
q.dequeue();
count--; // We processed a node, decrement count
if (count == 0) { // count will be zero when a level is completely processed
cout << endl;
count = q.size(); // Get the count of nodes at next level
}
}
}
// C++ Print levels
// Variable count tracks the number of nodes at a specific level.
// We know that first level has count '1'
// We first process nodes at the level, and enqueue its children in the queue.
// Once we have processed all nodes at a specific level (as indicated by count == 0),
// the queue then has nodes that belong to the next level
void levels(node * n) {
queue<node *> q;
q.enqueue(n);
int count = 1; // Queue has one node at this level
while(!q.empty()) {
node * n1 = q.top();
if (n1->l) {
q.enqueue(n1->l);
}
if (n1->r) {
q.enqueue(n1->r);
}
q.dequeue();
count--; // We processed a node, decrement count
if (count == 0) { // count will be zero when a level is completely processed
count = q.size(); // Get the count of node at next level
}
}
}
- osjunkie November 06, 2015