If we can get the next item at the same level, we are done. According to our previous knowledge , we can access this element using the first width traversal.
Now the only problem is how to check if we are the last element at any level. For this reason, we must add a delimiter (NULL in this case) to mark the end of the level.
Algorithm: 1. Put root in the queue.
2. Put NULL in the queue.
3. Until the queue is empty
4.x = select the first item from the queue
5. If x is not NULL 6. x-> rpeer <= the top element of the queue.
7. put the left and right child x of the queue
8. else
9. If the queue is not empty
10. put NULL in the queue
11. end, if 12. end, and 13. return
#include <queue> void print(tree* root) { queue<tree*> que; if (!root) return; tree *tmp, *l, *r; que.push(root); que.push(NULL); while( !que.empty() ) { tmp = que.front(); que.pop(); if(tmp != NULL) { cout << tmp=>val; //print value l = tmp->left; r = tmp->right; if(l) que.push(l); if(r) que.push(r); } else { if (!que.empty()) que.push(NULL); } } return; }
source share