Skip to content

Commit 51b2d67

Browse files
committed
BFS Iterative method right view
1 parent 1d7cfd9 commit 51b2d67

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

Trees/rightView.java

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,40 @@ void rightView(Node root,int level)
3838
rightView(root.left,level+1);
3939

4040
}
41-
41+
//iterative
42+
void rightView1(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==size-1)
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+
4275
}
4376

4477
class rightView{
@@ -49,6 +82,8 @@ public static void main(String[] args) {
4982
bt.root.right=new Node(5);
5083
bt.root.left.right=new Node(9);
5184
bt.root.right.left=new Node(7);
52-
bt.rightView(bt.root,1);
85+
bt.rightView(bt.root,1);
86+
bt.rightView1(bt.root);
87+
5388
}
5489
}

0 commit comments

Comments
 (0)