Created
December 16, 2017 08:34
-
-
Save rishi93/ec36cb53d0f2af0b8d29219d24d0efec to your computer and use it in GitHub Desktop.
Inorder, Preorder, Postorder traversals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Node{ | |
| int data; | |
| Node left, right; | |
| Node(int data){ | |
| this.data = data; | |
| this.left = null; | |
| this.right = null; | |
| } | |
| } | |
| class BinaryTree{ | |
| Node root; | |
| void printInOrder(Node curr){ | |
| if(curr == null){ | |
| return; | |
| } | |
| /* Print the left subtree */ | |
| printInOrder(curr.left); | |
| /* Print the root node */ | |
| System.out.print(curr.data + " "); | |
| /* Print the right subtree */ | |
| printInOrder(curr.right); | |
| } | |
| void printPreOrder(Node curr){ | |
| if(curr == null){ | |
| return; | |
| } | |
| /* Print the root node */ | |
| System.out.print(curr.data + " "); | |
| /* Print the left subtree */ | |
| printPreOrder(curr.left); | |
| /* Print the right subtree */ | |
| printPreOrder(curr.right); | |
| } | |
| void printPostOrder(Node curr){ | |
| if(curr == null){ | |
| return; | |
| } | |
| /* Print the left subtree */ | |
| printPostOrder(curr.left); | |
| /* Print the right subtree */ | |
| printPostOrder(curr.right); | |
| /* Print the root */ | |
| System.out.print(curr.data + " "); | |
| } | |
| } | |
| public class Test{ | |
| public static void main(String[] args){ | |
| BinaryTree tree = new BinaryTree(); | |
| tree.root = new Node(1); | |
| tree.root.left = new Node(2); | |
| tree.root.right = new Node(3); | |
| tree.root.left.left = new Node(4); | |
| tree.root.left.right = new Node(5); | |
| tree.root.right.left = new Node(6); | |
| tree.root.right.right = new Node(7); | |
| System.out.println("The Inorder traversal of the tree is:"); | |
| tree.printInOrder(tree.root); | |
| System.out.println(); | |
| System.out.println("The Preorder traversal of the tree is:"); | |
| tree.printPreOrder(tree.root); | |
| System.out.println(); | |
| System.out.println("The Postorder traversal of the tree is:"); | |
| tree.printPostOrder(tree.root); | |
| System.out.println(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment