Type Here to Get Search Results !

Tree Traversal (Inorder, Preorder and Postorder) in Java

0

 Tree Traversal (Inorder, Preorder and Postorder) in Java



Given Tree
Output

Inorder Traversal
40 20 50 10 60 30 70 

Preorder Traversal
10 20 40 50 30 60 70 

Inorder Traversal
40 50 20 60 70 30 10 

Inorder Traversal :

Algorithm Inorder (tree)

   1. Traverse the left subtree, i.e., call Inorder (left-subtree)

   2. Visit the root.

   3. Traverse the right subtree, i.e., call Inorder (right-subtree)

Preorder Traversal :

Algorithm Preorder (tree)
   1. Visit the root.
   2. Traverse the left subtree, i.e., call Preorder (left-subtree)
   3. Traverse the right subtree, i.e., call Preorder (right-subtree)

Postorder Traversal :

Algorithm Postorder(tree)
   1. Traverse the left subtree, i.e., call Postorder(left-subtree)
   2. Traverse the right subtree, i.e., call Postorder(right-subtree)
   3. Visit the root. 

Code

class Node {
	int key;
	Node left,right;  // uninitialized class object are initialized as null in Java.
	Node(int k)
	{
		key=k;
	}
}
public class PreandPostTraversal {
	public static void inOrder(Node root)
	{
		if(root!=null)
		{
			inOrder(root.left);
			System.out.print(root.key+" ");
			inOrder(root.right);
		}
		
	}
	public static void preOrder(Node root)
	{
		if(root!=null)
		{
			System.out.print(root.key+" ");
			preOrder(root.left);
			preOrder(root.right);
		}
		
	}
	public static void postOrder(Node root)
	{
		if(root!=null)
		{
			postOrder(root.left);
			postOrder(root.right);
			System.out.print(root.key+" ");
		}
		
	}
	public static void main(String[] args) {
		Node root=new Node(10);                   //    10
		root.left=new Node(20);                  //  20     30
		root.right=new Node(30);                // 40 50  60  70
		root.left.left=new Node(40);         // Inorder Traversal   : 40 20 50 10 60 30 70
		root.left.right=new Node(50);        // Preorder Traversal  : 10 20 40 50 30 60 70
		root.right.left=new Node(60);        // Postorder Traversal : 40 50 20 60 70 30 10
		root.right.right=new Node(70);
		System.out.println("Inorder Traversal");
		inOrder(root);
		System.out.print('\n');
		System.out.println("Preorder Traversal");
		preOrder(root);
		System.out.print('\n');
		System.out.println("Inorder Traversal");
		postOrder(root);
	}

}

Output

Inorder Traversal
40 20 50 10 60 30 70 
Preorder Traversal
10 20 40 50 30 60 70 
Postorder Traversal
40 50 20 60 70 30 10 

Post a Comment

0 Comments

Top Post Ad

Below Post Ad