-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree-InsertAndPrint.java
53 lines (42 loc) · 1.17 KB
/
BinaryTree-InsertAndPrint.java
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
/* Create method to insert a node in a Binary Tree and print the Tree. */
public class Node{
Node right, left;
int data;
Node(int value){
data = value;
}
private static Node insert(Node root, int data){
if(data > root.data){
//will be on the right
if(root.right == null){
root.right = new Node(data);
} else {
return insert(root.right, data);
}
} else {
//will be on the left
if(root.left == null){
root.left = new Node(data);
} else {
return insert(root.left, data);
}
}
return root;
}
private static void printTree(Node root){
if(root.left != null){
printTree(root.left);
}
System.out.println(root.data);
if(root.right != null){
printTree(root.right);
}
}
public static void main(String[] args){
Node tree = new Node(4);
insert(tree, 5);
insert(tree, 3);
insert(tree, 2);
printTree(tree);
}
}