Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions Algorithms/TreeSort.java
Original file line number Diff line number Diff line change
@@ -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);
}
}