How to print left 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 left view of this tree. Suppose if this is our binary tree



Then our output must be : 1 2 4

Because if we are left hand side of the tree then we can only see 1 2 and 4 .


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 PrintLeft(Node root,int level){
if(root==null){
return;
}
if(maxLevel<level){
System.out.println(root.data+" ");
maxLevel=level;
}
PrintLeft(root.left,level+1);
PrintLeft(root.right,level+1);
}

public static void printLeftView(Node root){
PrintLeft(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);

printLeftView(root);
}

}







Post a Comment

0Comments
Post a Comment (0)

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

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