LinkedIn Interview Question

Print a tree in level order (Newline after each level)

Interview Answer

Anonymous

Feb 23, 2015

void print_levelwise(tree *root) { queue<div>q; tree *tmp = NULL; if (root == NULL) return; q.push(root); q.push(NULL); while(!q.is_empty()) { tmp = q.pop(); // get and remove first element if (tmp == NULL) { printf("\n"); if (!q.is_empty()) q.push(NULL); } else { printf("%d\t", tmp->data); if (tmp->left) q.push(tmp->left); if (tmp->right) q.push(tmp->right); } } }</div>

1