Thursday, November 9, 2017

Tree Traversal Program In Java

We have 3 types of Traversals are there in Tree data structure.

1.Pre-Order Traversal
2.Post-Order Traversal
3.In-Order Traversal

In Pre-Order elements should be
Root Element , Left Child, Right Child

In Post-Order elements should be
Left Child, Right Child, Root Element

In In-Order Elements should be
Left Child, Root Element , Right Child
Here I have provided a Java program to define the above Traversal.

public class TreeTravese {
    public static void main(String[] args) {
 BinaryTree B = new BinaryTree();
 B.root = new NodeElement(1);
 B.root.left = new NodeElement(2);
 B.root.left.left = new NodeElement(6);
 B.root.left.right = new NodeElement(18);
 B.root.right = new NodeElement(24);
 B.root.right.right = new NodeElement(35);

 System.out.println("PreOrder: ");
 B.printPreOrder(B.root);
 System.out.println(" \nPostOrder");
 B.printPostOrder(B.root);
 System.out.println("\nInOrder");
 B.inOrder(B.root);
    }
}

class NodeElement {
    int Key;
    NodeElement left, right;

    public NodeElement(int item) {
 Key = item;
 left = right = null;
    }
}

class BinaryTree {
    NodeElement root;

    public BinaryTree() {
 root = null;
    }

    void printPostOrder(NodeElement node) {
 if (node == null)
     return;
 printPostOrder(node.left);
 printPostOrder(node.right);
 System.out.print(node.Key + " ");
    }

    void printPreOrder(NodeElement node) {
 if (node == null)
     return;
 System.out.print(node.Key + " ");
 printPreOrder(node.left);
 printPreOrder(node.right);
    }

    void inOrder(NodeElement node) {
 if (node == null) {
     return;
 }
 printPreOrder(node.left);
 System.out.print(node.Key + " ");
 printPreOrder(node.right);
    }    
}

No comments: