-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.java
More file actions
89 lines (78 loc) · 2.58 KB
/
BinaryTree.java
File metadata and controls
89 lines (78 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTree {
public static class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
public Node root;
public BinaryTree(){
root = null;
}
public void insertNode(int data) {
Node newNode = new Node(data);
if(root == null){
root = newNode;
return;
}
else {
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while(true) {
Node node = queue.remove();
if(node.left != null && node.right != null) {
queue.add(node.left);
queue.add(node.right);
}
else {
if(node.left == null) {
node.left = newNode;
queue.add(node.left);
}
else {
node.right = newNode;
queue.add(node.right);
}
break;
}
}
}
}
public void inorder(Node node) {
if(root == null){
System.out.println("Tree is empty");
return;
}
else {
if(node.left!= null)
inorder(node.left);
System.out.print(node.data + " ");
if(node.right!= null)
inorder(node.right);
}
}
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.insertNode(10);
System.out.println("Binary tree after first Insertion : ");
bt.inorder(bt.root);
bt.insertNode(15);
bt.insertNode(20);
System.out.println("\nBinary tree after second Insertion : ");
bt.inorder(bt.root);
bt.insertNode(11);
bt.insertNode(14);
System.out.println("\nBinary tree after third Insertion : ");
bt.inorder(bt.root);
bt.insertNode(17);
bt.insertNode(19);
System.out.println("\nBinary tree after fourth Insertion : ");
bt.inorder(bt.root);
}
}