-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
139 lines (121 loc) · 2.76 KB
/
BinarySearchTree.java
File metadata and controls
139 lines (121 loc) · 2.76 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
public class BinarySearchTree {
Node root;
public BinarySearchTree()
{
this.root = null;
}
public boolean Add(int value)
{
Node temp = new Node(value);
boolean result = this.Add(temp);
return result;
}
private boolean Add(Node tNode)
{
if(root == null)
{
this.root = tNode;
return true;
}
else
{
Node parent = null;
Node current = this.root;
int direction = 0;
while(current != null)
{
if(tNode.getData() == current.getData())
{
return false;
}
else if (tNode.getData() > current.getData())
{
parent = current;
current = current.getRightChild();
direction = 1;
}
else if(tNode.getData() < current.getData())
{
parent = current;
current = current.getLeftChild();
direction = 0;
}
}//END-OF-WHİLE
if(direction == 1)
{
parent.setRightChild(tNode);
}
else
{
parent.setLeftChild(tNode);
}
return true;
}
}
public boolean delete(int value)
{
Node tNode = new Node(value);
boolean result = delete(tNode);
return result;
}
private boolean delete(Node tNode)
{
if(this.root == null)
{
System.out.println("Ağaçta hiç düğüm yok!");
return false;
}
Node current = root;
Node parent = null;
while(current != null && current.getData() != tNode.getData())
{
parent = current;
if(current.getData() < tNode.getData())
{
current = current.getRightChild();
}
else
{
current = current.getLeftChild();
}
}
if(current == null)
{
System.out.println( tNode.getData() + " Bu değer ağaçta yok!");
return false;
}
if (current.getLeftChild() != null && current.getRightChild() != null)
{
Node successor = current.getRightChild();
Node successorParent = current;
while (successor.getLeftChild() != null)
{
successorParent = successor;
successor = successor.getLeftChild();
}
current.setData(successor.getData());
if (successorParent.getLeftChild() == successor) {
successorParent.setLeftChild(successor.getRightChild());
}
else
{
successorParent.setRightChild(successor.getRightChild());
}
return true;
}
Node child = (current.getLeftChild() != null) ? current.getLeftChild() : current.getRightChild();
if (parent == null)
{
root = child;
}
else if (parent.getLeftChild() == current)
{
parent.setLeftChild(child);
}
else
{
parent.setRightChild(child);
}
return true;
}
}