Skip to main content

Simplest iterative algorithm Post order traversal

package com.test;

import java.util.Stack;

public class PostOrderTraversal {

static class Node {
int data;
Node left, right;

Node(int item) {
data = item;
left = right;
}
}

private void pfIterate(Node root) {

Node prev = null;

Stack stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
if (root.left == null && root.right == null) {
System.out.print(root.data + " ");
prev = root;
} else if (prev == root.left || prev == root.right) {
System.out.print(root.data + " ");
prev = root;
} else {
stack.push(root);
if (root.right != null)
stack.push(root.right);
if (root.left != null)
stack.push(root.left);
}
}
}

public static void main(String[] args) {

// Let us create trees shown in above diagram
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);

new PostOrderTraversal().pfIterate(root);

}

}

Comments