Iterative Approach Of Preorder Traversal
Expl:
Push root .
Loop while Q is not empty , print data and push right node then left and remove from Q (last) so that we get the order
Code:
Deque<Node> q=new ArrayDeque<Node>();
q.add(root);
while(!q.isEmpty())
{
Node t=q.removeLast();
System.out.print(t.data+" ");
if(t.right!=null)
{
q.add(t.right);
}
if(t.left!=null)
{
q.add(t.left);
}
}
Push root .
Loop while Q is not empty , print data and push right node then left and remove from Q (last) so that we get the order
Code:
Deque<Node> q=new ArrayDeque<Node>();
q.add(root);
while(!q.isEmpty())
{
Node t=q.removeLast();
System.out.print(t.data+" ");
if(t.right!=null)
{
q.add(t.right);
}
if(t.left!=null)
{
q.add(t.left);
}
}
0 Comments:
Post a Comment