From 1e72b61e4fc213b0f6890b539695c900c9ae2780 Mon Sep 17 00:00:00 2001 From: rokingshubham1 <60622032+rokingshubham1@users.noreply.github.com> Date: Fri, 28 Oct 2022 00:22:55 +0530 Subject: [PATCH] Tree.java Code to traverse the tree into postorder, preorder & inorder traversing. --- java/Tree/tree.java | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 java/Tree/tree.java diff --git a/java/Tree/tree.java b/java/Tree/tree.java new file mode 100644 index 00000000..b0ef26c0 --- /dev/null +++ b/java/Tree/tree.java @@ -0,0 +1,68 @@ +import java.util.Scanner; + +public class Tree { + + static Scanner sc = null; + public static void main(String[] args) { + sc = new Scanner(System.in); + + Node root = createTree(); + inOrder(root); + System.out.println(); + preOrder(root); + System.out.println(); + postOrder(root); + System.out.println(); + } + + static Node createTree() { + + Node root = null; + System.out.println("Enter data: "); + int data = sc.nextInt(); + + if(data == -1) return null; + + root = new Node(data); + + System.out.println("Enter left for " + data); + root.left = createTree(); + + System.out.println("Enter right for "+ data); + root.right = createTree(); + + return root; + } + + static void inOrder(Node root) { + if(root == null) return; + + inOrder(root.left); + System.out.print(root.data+" "); + inOrder(root.right); + } + + static void preOrder(Node root) { + if(root == null) return; + System.out.print(root.data+" "); + preOrder(root.left); + preOrder(root.right); + } + + static void postOrder(Node root) { + if(root == null) return; + + postOrder(root.left); + postOrder(root.right); + System.out.print(root.data+" "); + } +} + +class Node { + Node left, right; + int data; + + public Node(int data) { + this.data = data; + } +}