Wednesday, June 11, 2014

Given a binary tree, print its perimeter.

node, left->most nodes from top to bottom, leaf nodes from left-> right, right->most nodes from bottom to top 

----------------------------1
                                 /   \
----------------------- 2       3 
                           /   \       /  \
-----------------4-----  5---6---7 
                    /   \            /     /  \
-------------8------9-----10---11--12 

should print: 
1-2-4-8-9-5-10-11-12-7-3 

5 because it doesn't have any children. 10 and 11 are children of 6 and 8 & 9 are children of 4. 



public static void perimeteTravrsal(Node root){
if(root == null) return;

perimeterTraversalUtil(root,true,true);
}


private static void perimeterTraversalUtil(Node root, boolean isLeft, boolean isRight){

if(root == null) return;

if(isLeft || root.left == null && root.right == null)
{
System.out.print(root.val+"->");
}

perimeterTraversalUtil(root.left, isLeft?true:false, false);

perimeterTraversalUtil(root.right, false, isRight?true:false);

if(isRight  && !isLeft && !(root.left == null && root.right == null))
{
System.out.print(root.val+"->");
}

}

No comments:

Post a Comment