From 5486f445137c3148029cfd0ec55e84a0f2560008 Mon Sep 17 00:00:00 2001 From: himanshukumar4642 Date: Tue, 15 Oct 2019 14:15:59 +0530 Subject: [PATCH] binary tree in java --- .../Binary Tree/java/binary tree in java.cpp | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Data Structures/Binary Tree/java/binary tree in java.cpp diff --git a/Data Structures/Binary Tree/java/binary tree in java.cpp b/Data Structures/Binary Tree/java/binary tree in java.cpp new file mode 100644 index 00000000..bbd7675f --- /dev/null +++ b/Data Structures/Binary Tree/java/binary tree in java.cpp @@ -0,0 +1,93 @@ + +class Node +{ + int key; + Node left, right; + + public Node(int item) + { + key = item; + left = right = null; + } +} + +class BinaryTree +{ + Node root; + + BinaryTree() + { + root = null; + } + + void printPostorder(Node node) + { + if (node == null) + return; + + printPostorder(node.left); + + + printPostorder(node.right); + + + System.out.print(node.key + " "); + } + + void printInorder(Node node) + { + if (node == null) + return; + + + printInorder(node.left); + + + System.out.print(node.key + " "); + + + printInorder(node.right); + } + + + void printPreorder(Node node) + { + if (node == null) + return; + + + System.out.print(node.key + " "); + + + printPreorder(node.left); + + + printPreorder(node.right); + } + + + void printPostorder() { printPostorder(root); } + void printInorder() { printInorder(root); } + void printPreorder() { printPreorder(root); } + + + 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); + + System.out.println("Preorder traversal of binary tree is "); + tree.printPreorder(); + + System.out.println("\nInorder traversal of binary tree is "); + tree.printInorder(); + + System.out.println("\nPostorder traversal of binary tree is "); + tree.printPostorder(); + } +} +