Given a binary tree, print boundary nodes of the binary tree Anti-Clockwise starting from the root. For example, boundary traversal of the following tree is “20 8 4 10 14 25 22″
Solution:
public class PrintBoundary {
Node root;
public static void main(String[] args) {
PrintBoundary tree=new PrintBoundary();
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(14);
tree.root.right = new Node(22);
tree.root.right.right = new Node(25);
tree.printBoundary(tree.root);
}
private void printBoundary(Node root2) {
if(root2==null)
return;
System.out.println(" "+root2.data);
if(root2.left!=null)
printLeftBoundary(root2.left,"left");
if(root2.right!=null)
printLeftBoundary(root2.right,"right");
// TODO Auto-generated method stub
}
private void printLeftBoundary(Node root3, String string) {
if(root3==null)
return;
if(string=="left")
{
System.out.println(" "+root3.data);
printLeftBoundary(root3.left, "left");
printLeftBoundary(root3.right, "null");
}
else if(string=="right")
{
printLeftBoundary(root3.left, "null");
printLeftBoundary(root3.right, "right");
System.out.println(" "+root3.data);
}
else{
if(root3.left==null && root3.right==null)
{
System.out.println(" "+root3.data);
return;
}
printLeftBoundary(root3.left, "null");
printLeftBoundary(root3.right, "null");
}
// TODO Auto-generated method stub
}
}