public void inorderNonRecursive(TreeNode rootnode)
{
Stack stack =new Stack();
Processable info;
TreeNode temp;
temp=rootnode;
while(true)
{
while(temp!=null)
{
stack.push(temp);
temp=temp.left;
}
if(stack.isEmpty())
break;
temp=(TreeNode)stack.pop();
info=(Processable)temp.data;
info.process();
temp=temp.right;
}
}
Subscribe to:
Post Comments (Atom)
3 comments:
Thank you :)
Glad I stumbled on your site, looks very helpful in preparing for interviews.
I think the code can be made simpler. Here is my attempt.
public void nonRecursiveTraverse() {
Stack s = new Stack();
s.push(root);
while(!s.isEmpty()) {
Node n = s.pop();
System.out.println(n.value);
if (n.left != null)
s.push(n.left);
if (n.right != null)
s.push(n.right);
}
}
Post a Comment