How to print right view of binary tree in java

0

 


If you are preparing for the technical interview then prepare this question . It is one of the most asked question in the interviews. In this problem you are given a binary tree and you have to print the right view of this tree. Suppose if this is our binary tree



Then our output must be : 1 3 6

Because if we are at the right hand side of the tree then we can only see 1 3 and 6 .


Java Code :



class Node{

int data;
Node left;
Node right;
Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
class HindiCodingCommunity{

public static int maxLevel=0;

public static void printRight(Node root,int level){
if(root==null){
return;
}
if(maxLevel<level){
System.out.println(root.data+" ");
maxLevel=level;
}
printRight(root.right,level+1);
printRight(root.left,level+1);
}

public static void printRightView(Node root){
printRight(root,1);
}

public static void main(String args[])
{
Node root = new Node(1);
root.left = new Node(2);
root.right= new Node(3);

root.left.left= new Node(4);
root.right.left= new Node(5);
root.right.right= new Node(6);

printRightView(root);
}

}





Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !