Sunday, March 4, 2012

Left and Right View of a Binary Tree.


Write code to get the left and right view of a binary Tree.




Left View: 50, 17, 9, 14, 12
Right View: 50 76, 54, 72, 67


Approach:
1. Keep track of each level of the binary tree using a marker node.
2. while doing a level order traversal of the binary tree if we hit the marker node, then if the queue is non-empty then insert the head of node in the leftViewList.
3. if the current node that we pulled out of queue is not marker, but its next node is marker then put the current node in the rightViewList.


In the end print the left and right view lists.




Code input/output:
printing inorder: 
9 12 14 17 19 23 50 54 67 72 76 
Printing left View: 
50 17 9 14 12 
Printing right view: 
50 76 54 72 67 

1 comment: