Print a Binary tree in level order with new line after every level

Problem Given a binary tree, you have to print level order traversal of the tree (left child then right child) but every next level has to be printed in next line. Example If the given tree is 5 10 15 56 47 12 42 ```Then the output should be 5 10 15 56 47 12 42 ### Solution Here is the approach: 1. Start with a root node. Add it to a new list. [Read More]

Binary Tree Level-Order Traversal Using Depth First Search (DFS) [Not to USE BFS]

Given a binary tree, print out the tree in level order (ie, from left to right, level by level). Output a newline after the end of each level. Breadth First Search (BFS) is not allowed. We have already seen how to do level order traversal here. Example So consider the tree: 1 / \ 2 3 / \ / \ 4 5 6 7 The BFS or level order traversal here is : [Read More]

BFS (Breadth first search ) OR Level Order Traversal on tree

Algorithm Starting at some arbitrarily chosen vertex s (s stands for start vertex) , we mark v so that we know we’ve visited it, process v, and  then visit i.e. mark the vertex as visited and process all of v’s neighbors.  Now that we’ve visited and processed all of v’s neighbors,  we need to visit and process all of v’s neighbors neighbors Example So consider the tree: [Read More]

Print a Binary Tree in Zig Zag Level Order or spiral order

Question: Print a binary tree in zig-zag level order. Zig-zag means print 1st level from left to right, then 2nd level right to left and alternate thereafter. Example: zig-zag level order traversal of below tree will be 0 2 1 3 4 5 6 14 13 12 11 10 9 8 7 Solution1 - Iterative solution Answer: We usually use a queue for level order traversal of a queue. If we want to use the same here, how will we change direction of traversal on every alternate level? [Read More]