From 54531a725a180b6f5a40c1287df04d1b94a59f21 Mon Sep 17 00:00:00 2001 From: Kasun <31097851+KasunAtSLIIT@users.noreply.github.com> Date: Sun, 15 Oct 2023 13:17:51 +0530 Subject: [PATCH] Create TreeSort.java --- Algorithms/TreeSort.java | 90 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Algorithms/TreeSort.java diff --git a/Algorithms/TreeSort.java b/Algorithms/TreeSort.java new file mode 100644 index 0000000..ca9a216 --- /dev/null +++ b/Algorithms/TreeSort.java @@ -0,0 +1,90 @@ +// Java program to +// implement Tree Sort +class TreeSort +{ + + // Class containing left and + // right child of current + // node and key value + class Node + { + int key; + Node left, right; + + public Node(int item) + { + key = item; + left = right = null; + } + } + + // Root of BST + Node root; + + // Constructor + TreeSort() + { + root = null; + } + + // This method mainly + // calls insertRec() + void insert(int key) + { + root = insertRec(root, key); + } + + /* A recursive function to + insert a new key in BST */ + Node insertRec(Node root, int key) + { + + /* If the tree is empty, + return a new node */ + if (root == null) + { + root = new Node(key); + return root; + } + + /* Otherwise, recur + down the tree */ + if (key < root.key) + root.left = insertRec(root.left, key); + else if (key > root.key) + root.right = insertRec(root.right, key); + + /* return the root */ + return root; + } + + // A function to do + // inorder traversal of BST + void inorderRec(Node root) + { + if (root != null) + { + inorderRec(root.left); + System.out.print(root.key + " "); + inorderRec(root.right); + } + } + void treeins(int arr[]) + { + for(int i = 0; i < arr.length; i++) + { + insert(arr[i]); + } + + } + + // Driver Code + public static void main(String[] args) + { + TreeSort tree = new TreeSort(); + int arr[] = {5, 4, 7, 2, 11}; + tree.treeins(arr); + tree.inorderRec(tree.root); + } +} +