Skip to content

Commit f135ad8

Browse files
authored
Merge pull request #471 from Shubh1006/tree
Tree
2 parents c64a16b + 03d29ad commit f135ad8

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

java/sorting/tree_sort.java

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// Java program to
2+
// implement Tree Sort
3+
class GFG
4+
{
5+
6+
// Class containing left and
7+
// right child of current
8+
// node and key value
9+
class Node
10+
{
11+
int key;
12+
Node left, right;
13+
14+
public Node(int item)
15+
{
16+
key = item;
17+
left = right = null;
18+
}
19+
}
20+
21+
// Root of BST
22+
Node root;
23+
24+
// Constructor
25+
GFG()
26+
{
27+
root = null;
28+
}
29+
30+
// This method mainly
31+
// calls insertRec()
32+
void insert(int key)
33+
{
34+
root = insertRec(root, key);
35+
}
36+
37+
/* A recursive function to
38+
insert a new key in BST */
39+
Node insertRec(Node root, int key)
40+
{
41+
42+
/* If the tree is empty,
43+
return a new node */
44+
if (root == null)
45+
{
46+
root = new Node(key);
47+
return root;
48+
}
49+
50+
/* Otherwise, recur
51+
down the tree */
52+
if (key < root.key)
53+
root.left = insertRec(root.left, key);
54+
else if (key > root.key)
55+
root.right = insertRec(root.right, key);
56+
57+
/* return the root */
58+
return root;
59+
}
60+
61+
// A function to do
62+
// inorder traversal of BST
63+
void inorderRec(Node root)
64+
{
65+
if (root != null)
66+
{
67+
inorderRec(root.left);
68+
System.out.print(root.key + " ");
69+
inorderRec(root.right);
70+
}
71+
}
72+
void treeins(int arr[])
73+
{
74+
for(int i = 0; i < arr.length; i++)
75+
{
76+
insert(arr[i]);
77+
}
78+
79+
}
80+
81+
// Driver Code
82+
public static void main(String[] args)
83+
{
84+
GFG tree = new GFG();
85+
int arr[] = {5, 4, 7, 2, 11};
86+
tree.treeins(arr);
87+
tree.inorderRec(tree.root);
88+
}
89+
}

0 commit comments

Comments
 (0)