1. Traverse the left subtree by recursively calling the post-order function.
2. Traverse the right subtree by recursively calling the post-order function.
3. Display the data part of the root (or current node).
class Node {
int key;
Node left, right;
public Node(intitem) {
key = item;
left = right = null;
}
}
class BinaryTree {
/** Root of Binary Tree*/
Node root;
BinaryTree() {
root = null;
}
/** PostOrder binary tree traversal. */
void printPostorder(Node node) {
if(node==null) {
return;
}
printPreorder(node.left);
printPreorder(node.right);
System.out.print(node.key +" ");
}
/** Call PostOrder traversal. */
void printPostorder() {
printPreorder(root);
}
}
public class PostorderTraversal {
public static void main(String[] args) {
BinaryTree bTree = newBinaryTree();
bTree.root = new Node(1);
bTree.root.left = new Node(2);
bTree.root.right = new Node(3);
bTree.root.left.left = new Node(4);
bTree.root.left.right = new Node(5);
bTree.root.left.left.left = new Node(6);
bTree.root.left.left.right = new Node(7);
System.out.println("PostOrder traversal of binary tree is ");
bTree.printPostorder();
}
}
No comments:
Post a Comment