Tuesday, July 12, 2016

Binary Tree Traversing algorithms

There could be surprise when  people ask you to print binary tree in some special ways .


 There following techniques for that

1. Recursion
2. Using stack/queue for non-recursion
3. Keeping track of  (X,Y) coordinates (start root with (0,0) ) of node  like when you go left decrease x , when you go right increase X

Following could be possible set of questions for iterating over binary tree (is may not be BST ).

Depth First : (with or without recursion )

1. Pre-order
2. In-order
3. Post-order

Breadth First :

1. Breadth first  - level order
2. Breadth first  - zig-zag , or alternate direction in level order or spiral order traversal

Special Order 

1. Print node or  sum of  nodes ,  with vertical columns in the binary tree.
2. Print sum of nodes which in diagonal of binary  tree.
3 .Print all nodes in circumference of the tree  means all nodes in root left , right and bottom borders .
4. Print bottom view of binary tree.
5. Print top view of binary tree.
6. print inner nodes of binary tree.
7. print outer layer of binary tree
8. print only leaf nodes
9. print periphery of binary tree



Other oddities could be there like

If you can write pre-order, in-order , post-order using recursion  always think how you can do using it stack or without recursion .

Same logics if possible apply for n-Array tree.



We will solve above all one by one in next blogs .