Printing binary tree

Problem

Write a function to print the rows of a binary tree, terminating each row with a carriage return.

Answer

This question can be solved using the Breadth First Search.

Using std::list as a queue, we can print each node and print the carriage return when we change the level.

To do so, we need to remember the number of children at each level.

Overall running time will be $O ( N )$, where N is the number of nodes in the tree.


Here is the complete code.



Practice statistics

08:46: to code up the solution

UPDATE (2019-07-18): solved the problem in python. using deque


Practice statistics

25:00: to write code
5:00: to fix typo


UPDATE(2022-06-14): Solved again in python. This time I used just list and used pop(0) as a dequeue replacement. Had a bug in the code and took more than 9 mins to fix it.


9:30: coding
3:00: test code.

Comments

Popular posts from this blog

Planting flowers with no adjacent flower plots

Find the maximum number of bomb that can be detonated