Skip to content

Commit 6f85af1

Browse files
committed
LEFT VIEW TREE Iterative
1 parent d0eb364 commit 6f85af1

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

Trees/leftView.java

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
import java.util.LinkedList;
2+
import java.util.Queue;
3+
4+
import javax.management.Query;
5+
16
class Node
27
{
38
int data;
@@ -33,17 +38,53 @@ void leftView(Node root,int level)
3338
leftView(root.left,level+1);
3439
leftView(root.right,level+1);
3540
}
41+
//iterative
42+
void leftView1(Node root)
43+
{
44+
if(root==null)
45+
return;
46+
Queue<Node> q=new LinkedList<>();
47+
q.add(root);
48+
while(true)
49+
{
50+
int size=q.size();
51+
if(size==0)
52+
{
53+
break;
54+
}
55+
for(int i=0;i<size;i++)
56+
{
57+
Node temp=q.remove();
58+
if(i==0)
59+
{
60+
System.out.print(temp.data+" ");
61+
}
62+
if(temp.left!=null)
63+
{
64+
q.add(temp.left);
65+
}
66+
if(temp.right!=null)
67+
{
68+
q.add(temp.right);
69+
}
70+
}
71+
72+
}
73+
}
74+
3675

3776
}
3877

39-
class btree{
78+
class leftView{
4079
public static void main(String[] args) {
4180

4281
BinaryTree bt=new BinaryTree(2);
4382
bt.root.left=new Node(3);
4483
bt.root.right=new Node(5);
4584
bt.root.left.right=new Node(9);
4685
bt.root.right.left=new Node(7);
86+
bt.leftView(bt.root,1);
87+
bt.leftView1(bt.root);
4788

4889
}
4990
}

0 commit comments

Comments
 (0)