8000 Added program to implement binary tree creation. · AllAlgorithms/java@da262eb · GitHub
[go: up one dir, main page]

Skip to content

Commit da262eb

Browse files
coderquillabranhe
authored andcommitted
Added program to implement binary tree creation.
1 parent 6409e8c commit da262eb

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

data-structures/BinaryTree.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/* Class containing left and right child of current
2+
node and key value*/
3+
class Node
4+
{
5+
int key;
6+
Node left, right;
7+
8+
public Node(int item)
9+
{
10+
key = item;
11+
left = right = null;
12+
}
13+
}
14+
15+
// A Java program to make Binary Tree
16+
class BinaryTree
17+
{
18+
// Root of Binary Tree
19+
Node root;
20+
21+
// Constructors
22+
BinaryTree(int key)
23+
{
24+
root = new Node(key);
25+
}
26+
27+
BinaryTree()
28+
{
29+
root = null;
30+
}
31+
32+
public static void main(String[] args)
33+
{
34+
BinaryTree tree = new BinaryTree();
35+
36+
/*create root*/
37+
tree.root = new Node(1);
38+
39+
/* following is the tree after above statement
40+
41+
1
42+
/ \
43+
null null */
44+
45+
tree.root.left = new Node(2);
46+
tree.root.right = new Node(3);
47+
48+
/* 2 and 3 become left and right children of 1
49+
1
50+
/ \
51+
2 3
52+
/ \ / \
53+
null null null null */
54+
55+
56+
tree.root.left.left = new Node(4);
57+
/* 4 becomes left child of 2
58+
1
59+
/ \
60+
2 3
61+
/ \ / \
62+
4 null null null
63+
/ \
64+
null null
65+
*/
66+
}
67+
}

0 commit comments

Comments
 (0)
0