-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.java
More file actions
64 lines (59 loc) · 1.46 KB
/
BinaryTree.java
File metadata and controls
64 lines (59 loc) · 1.46 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
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data=data;
}
}
public class BinaryTree {
Node root;
public void insert(int data){
// if(root==null){
// root=new Node(data);
// }else if(data<root.data){
// root.left.data=data;
// }
root=insertRec(root, data);
}
public Node insertRec(Node root,int data){
if(root==null){
root=new Node(data);
}else if(data<root.data){
root.left =insertRec(root.left, data);
}else if(data>root.data){
root.right=insertRec(root.right, data);
}
return root;
}
public void inorder(){
inorderRec(root);
}
public void inorderRec(Node root){
if(root !=null){
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
}
}
public void preorder(){
preorderRec(root);
}
public void preorderRec(Node root){
if(root !=null){
System.out.print(root.data + " ");
preorderRec(root.left);
preorderRec(root.right);
}
}
public void postorder() {
postorderRec(root);
}
public void postorderRec(Node root) {
if (root != null) {
postorderRec(root.left);
postorderRec(root.right);
System.out.print(root.data + " ");
}
}
}