3. Output level wise #
Created Monday 27 January 2020
As we did in the take level part, use the queue STL. And do it.
code:
template
queue<TreeNode
nodesPending.push(root); // obviously pending, we have not printed it’s children.
// Another reason is that if we don’t do this, then queue will not be systematic.
// for optimization
int data; // for relevance
int n; // number of children
TreeNode
// start printing the children while (nodesPending.size() != 0) { node = nodesPending.front(); // current root’s data n = node->children.size(); data = node->data;
if (n == 0) cout << node->data << “: Leaf\n”; else { cout << "Children of " << data << ": "; for (int i = 0; i < n; i++) { cout << node->children.at(i)->data << ", "; nodesPending.push(node->children.at(i)); } cout << “\b\b \n”; }
nodesPending.pop(); } }