private void iterativePostOrder(Node root)
{
if (root == null)
{
return;
}
java.util.Stack<node> nodeStack = new java.util.Stack<node>();
Node cur = root;
while (true)
{
if (cur != null)
{
if (cur.right)
{
nodeStack.push(cur.right);
}
nodeStack.push(cur);
cur = cur.left;
continue;
}
if (nodeStack.empty())
{
return;
}
cur = nodeStack.peek();
nodeStack.pop();
if (cur.right && !nodeStack.empty() && cur.right == nodeStack.peek())
{
nodeStack.pop();
nodeStack.push(cur);
cur = cur.right;
}
else
{
System.out.print(cur.val);
System.out.print(" ");
cur = null;
}
}
}</node></node>
Used this demo
Converter[
^]