-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.java
More file actions
99 lines (98 loc) · 2.97 KB
/
Copy pathBinaryTree.java
File metadata and controls
99 lines (98 loc) · 2.97 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
90
91
92
93
94
95
96
97
98
99
import java.util.ArrayList;
public class BinaryTree {
static class Node {
Student data;
Node left;
Node right;
public Node(Student data) {
this.data = data;
}
}
private Node root;
public BinaryTree() {
root = null;
}
public void add(Student student) {
root = insert(root, student);
}
private Node insert(Node current, Student student) {
if (current == null) {
return new Node(student);
}
else {
if (student.StudentID < current.data.StudentID) {
current.left = insert(current.left, student);
}
else if (student.StudentID > current.data.StudentID) {
current.right = insert(current.right, student);
}
}
return current;
}
public void print(){
inorder(root);
}
private void inorder(Node current) {
if (current == null){
return;
}
inorder(current.left);
System.out.println(current.data.toString());
inorder(current.right);
}
//2 рівень
public ArrayList<Student> find(int course,String hobby) {
ArrayList<Student> list = new ArrayList<>();
if (root == null){
System.out.println("Tree empty!");
}
search(root,course,hobby,list);
return list;
}
private void search(Node current, int course, String hobby, ArrayList<Student> list) {
if (current == null){
return;
}
search(current.left, course, hobby, list);
if (current.data.Course == course && current.data.Hobby.equals(hobby)){
list.add(current.data);
}
search(current.right, course, hobby, list);
}
//3 рівень
public void delete(int course, String hobby) {
root = remove(root, course, hobby);
}
private Node remove(Node current, int course,String hobby){
if (current == null){
return null;
}
current.left = remove(current.left, course, hobby);
current.right = remove(current.right, course, hobby);
if (current.data.Course == course && current.data.Hobby.equals(hobby)){
if (current.left == null && current.right == null){
return null;
}
else if (current.left == null){
current = current.right;
return current;
}
else if (current.right == null){
current = current.left;
return current;
}
current.right = replaceNode(current, current.right);
}
return current;
}
private Node replaceNode(Node deleteNode,Node current){
if (current.left != null){
current.left = replaceNode(current.left, current);
}
else {
deleteNode.data = current.data;
current = current.right;
}
return current;
}
}