generated from github/codespaces-blank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.java
65 lines (61 loc) · 1.42 KB
/
BinaryTree.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
54
55
56
57
58
59
60
61
62
63
64
65
class node{
int data;
node lchild;
node rchild;
public node(int data){
this.data = data;
lchild = rchild = null;
}
}
public class BinaryTree{
node head;
public BinaryTree(){
head = null;
}
public void insert(int x){
node nl = new node(x);
node current = head;
node parent = current;
if(head == null){
head = nl;
return;
}
while(true){
if(x <= current.data){
parent = current;
current = current.lchild;
if(current == null){
parent.lchild = nl;
return ;
}
}
else{
parent = current;
current = current.rchild;
if(current == null){
parent.rchild = nl;
return ;
}
}
}
}
public void inorder(){
inorder(head);
}
public void inorder(node current){
if (current != null) {
inorder(current.lchild);
System.out.println(current.data);
inorder(current.rchild);
}
}
public static void main(String args[]){
BinaryTree b = new BinaryTree();
b.insert(5);
b.insert(2);
b.insert(6);
b.insert(1);
b.insert(3);
b.inorder();
}
}