BFS:
Is it possible that a solution exists using only one single queue? Yes, you bet. The single queue solution requires two extra counting variables which keep tracks of the number of nodes in the current level (Nodesincurrentlevel) And the next level (Nodesinnextlevel). When we pop a node off the queue, we decrementNodesincurrentlevelByOne. When we push its child nodes to the queue, We IncrementNodesinnextlevelByTwo. WhenNodesincurrentlevelReaches0, We know that the current level has ended, therefore we print an endline here
void printLevelOrder(BinaryTree *root) { if (!root) return; queue<BinaryTree*> nodesQueue; int nodesInCurrentLevel = 1; int nodesInNextLevel = 0; nodesQueue.push(root); while (!nodesQueue.empty()) { BinaryTree *currNode = nodesQueue.front(); nodesQueue.pop(); nodesInCurrentLevel--; if (currNode) { cout << currNode->data << " "; nodesQueue.push(currNode->left); nodesQueue.push(currNode->right); nodesInNextLevel += 2; } if (nodesInCurrentLevel == 0) { cout << endl; nodesInCurrentLevel = nodesInNextLevel; nodesInNextLevel = 0; } }}
DFS:
void printLevel(BinaryTree *p, int level) { if (!p) return; if (level == 1) { cout << p->data << " "; } else { printLevel(p->left, level-1); printLevel(p->right, level-1); }} void printLevelOrder(BinaryTree *root) { int height = maxHeight(root); for (int level = 1; level <= height; level++) { printLevel(root, level); cout << endl; }}
Printing a binary tree in level orders