Java Datastructure
Java Datastructure
A data structure is created by taking existing data and building a structure according to a defined standard.
1.1 Steps in creating a data structure .
1. Create an abstract data type (ADT ) definition for each data structure.
2. Implement the defined ADT by writing a program in a computer language such as... C language
Java as defined ( ADT ) which was built upon step 1.
3. After implementation , a new data structure ( ADT ) will be obtained, based on the definition created
in step 1.
Abstract Data Type ( &
ADT )
definitions of each data structure , which consist of:
1. -
Set of data
2. %
Data relationships AUP + implement I data structure
operater code stat
3. Group of actors Lu
↑ 2. Data relationship: Data is stored so that later entered data is retrieved first.
3. Group of actors
<-
=> Operater 2 ว
- -
enquene
dequence //
ad - Push : Enter data.
=>
We will start with two simple abstract data types : Collection and List.
Collection ADT
1. A set of data, such as {3, 1, 7, 15, 29}.
-
2. Data relationships: Data is stored like a data container that only allows addition and deletion.
-
-operater
3. Group of actors ่ม อไม่ไ ด ้ ไ ่ได
-
Array & เ
ูลไ
สอperม
- add ( Object O ) : Add data O to the bin. Array List & เ ม อ
①recallinte *
#. . . # # แต
#
public ArrayCollection ()
{
data = new Object [ 1 ] ;
size = 0;
}
public void add ( Object e )
{
capacity ( size + 1 ) ; // If the array is full, it will simulate expanding first, then add new data.
data [ size ] = e;
size ++ ;
}
public int size ()
{ return size; }
{
if ( a > data . length )
{
Object [] arr = new Object [ 2 * data . length ] ;
for ( int i = 0; i < size; i ++)
arr [ i ] = data [ i ] ;
data = arr;
}
}
} // end of class ArrayCollection
{
if ( a > data . length )
{
Object [] arr = new Object [ 2 * data . length ] ;
for ( int i = 0; i < size; i ++)
arr [ i ] = data [ i ] ;
data = arr;
}
}
{
// Move all elements after position j up 1 position.
for ( int j = i + 1; j < size; j ++)
{ data [ j - 1 ] = data [ j ] ; }
size -- ;
data [ size ] = null;
}
}
public Object get ( int i ) // Will not retrieve data if i is a location where no data exists.
{
if ( i > = 0 && i < = size - 1 )
{
return data [ i ] ;
}
}
{
data [ i ] = e;
}
}
[Link] ( ob1 ) ;
[Link] ( ob2 ) ;
a . add ( 1,ob3 ) ;
a . add ( 0,ob4 ) ;
a . remove ( ob1 ) ;
System . out . print ( a . size () ) ;
boolean c = a . contains ( ob2 ) ;
a . remove ( 1 ) ;
}
}
Because a list of data is ordered by entry, the method for removing data at the desired position is
to shift all elements immediately following the desired position up one position, so that the new element
overlaps the element being deleted. For example, to delete the position at the 'i'th position.
อยา
กแทร
#st
#- At
Because the list data is ordered by placement, the method for adding to a specific position is to shift
the element at the desired insertion position and all subsequent elements down one position to create space
for the insertion.
For example, we want to insert data at the i- th position.
Whether deleting or inserting data, the data is shifted a maximum of n characters using only a single for loop .
Therefore, the complexity is only O(n).
End-of-chapter exercises
ถ้
Write a program to create a data structure list using an array , with the following details:
1. Create a Collection interface to specify the list of necessary methods , which are:
- add ( Object o ) to add the desired data.
- remove ( Object o ) is used to delete the desired data.
- contain s ( Object o ) for searching for the desired information.
- isEmpty () To check if there is any data inside this data reservoir.
- size () is used to check the quantity of data.
- add ( int i, Object e ) to add data at position i.
- remove ( int i ) deletes the data at position i.
- get ( int i ) retrieves data at position i.
- set ( int i, Object e ) replaces the data at position i with the data e.
2. Create an ArrayList class to construct a list data structure using an array , implementing it from the
List interface and making the abstract methods within that interface complete methods .
3. Create a Test Class named Test2 to verify the data storage operation. The results will be displayed
on the screen after the following operations:
3.1 Add integer data nodes with values 20 and 30.
3.2 Delete the data node with the value 20 from the data bin.
3.3 Delete the data node with a value of 50 from the bin.
3.4 Find the data node that has a value of 30 in the data bucket.
Chapter 2 Linked List
The next data structure is a Linked List , which is a data structure that connects nodes together in a chain.
There are 3 types .
- Singly Linked List
- Circular Linked List
- Doubly Linked List
2.1 Singly Linked List
The following conditions apply as stated in this document:
1. There must be a pointer pointing to the first node, in this case named 'first'.
2. The last node in the `next` section must be `null` , indicating that there is no address for the next node.
3. The first indicator It is not movable; it must point to the first node, which serves as the pointer for
accessing the Linked List. To access any node in the Linked List , one must enter through the first node.
<null
The difference between a Linked List and an Array is:
1. An array contains contiguous elements in its addresses , but a linked list doesn't necessarily
require contiguous addresses .
2. The data in an array must be of the same type, but in a linked list, the data is of the same type.
They don't have to be the same type.
3. Once an array is reserved , its number of reserved elements cannot be expanded or contracted.
However, a linked list can be expanded indefinitely.
2.1.1 Nodes
Since a linked list consists of nodes connected to each other, we must first understand the nodes before
creating a linked list.
A node consists of two parts.
- data section, as shown in the image below, is the first node in the data section , storing the data '
a '.
- The part that stores the address of the next node ( next ) is shown in the figure below. The first
node's part, `next`, stores the address of the next node, which is the address of the node
containing data (b).
(store address of b)
- If the ` next` node doesn't yet store the address of any node, it will look like the image below.
object 3 = Sty
ให้ ก 28 แ ม
To create a node, you need a node class. The node class has two instance variables , `data` and
`next` , which store the data and addresses of the next node respectively. Therefore, it has four instance
methods . Methods for retrieving ( get ) and replacing ( set ) data on the `data` element and `next` element.
node ประกอบ 2 ว
-dat
ส า ดลก
ง
-nex
&
7
ra2 ser
surfe data = obj; constructe
return เ น
next = n;
}
Gi public void setNext ( MyNode n ) {
↓
next = n;ใส่ดมาต
=
ต วห
เขา
} method
+
public void setData ( Object d ) {
=
=
-
data = d; ↓
}
public MyNode getNext () {
-
ส่
ร้
ข้
ตั
ช่
ม่
ร้
ล่
ลู
น้
กี
return next;
}
public Object getData () {
= >
return data;
}
}
2.1.2 Creating a Singly Linked List
1. Start with an empty Linked List or an empty trash can.
empty linked list means that `first` has no next node to point to; therefore, `first = null;`
2. Insert the first element into a linked list ; for example, to insert the element ' a ' into an empty bin.
Before adding data ' a ' to a Linked List , a node must be created to store the data ' a '.
=>
Mynode t = new Mynode ( a,/
null ) ; ( 1A
)
Or you can combine commands ( 1 ) and ( 2 ) into one command as in the command above.
When `start` points to the last node, set the `next` portion of `start` to the address of the newly created
node, which has a value of 1, as shown in the image below.
First, create a new node that stores the value 4 , and set the `next` clause of this new node to the
address of the first node. This address was originally stored in the variable `first` , as shown in the image and
command below.
Then, change `first` to point to the new node instead, because now the new node is the first node in
the Linked List , a c c o r d i n g t o t h e c o m m a n d a n d
image below. That is, the variable ` first` stores the address of the new node, which is stored in the variable
`p`.
Move `first` to point to the second node instead of the first node, as shown in the command and
image below.
5.2 Delete the intermediate node .
If we need to enclose the node with the value of 3 below, which is the middle node.
first pointer. Since it cannot be moved, another pointer must be created to move to the desired
location for deletion. In this case, this pointer is named ' start'. Because the 'next' part of the node preceding
the one to be deleted must point to the node following the one to be deleted, an additional pointer is needed
to move it before the ' start' pointer . In this case, that pointer is named ' pre'.
Before moving the pointers, set pre and start equal to first , meaning that pre and start begin pointing
to the first node .
Before moving the start value, the preset value must be the same as the original start value . That is,
when the start value is moved, the preset value will move immediately after the start value , as shown in the
command and image below.
Then, set the value in the 'next' section of the node pointed to by the 'pre' pointer to the address of
the node next to the node to be deleted, which is pointed to by the 'start' pointer ( the node with a value of 3).
As shown in the instructions and image below.
5.3 Delete the tail node .
To delete the node below that has a value of 5 , which is the last node.
Before moving the pointers, set pre and start equal to first , meaning that pre and start begin pointing
to the first node .
Move the pointers `pre` and `start` together. `start` will stop at the node to be deleted, which is the
last node, and `pre` will stop at the node before the one ` start` pointed to, as shown in the command and the
two figures below.
To remove the last node, which stores the value 5 , we set the ` next` attribute of the node preceding
the one to be removed, which is pointed to by the `pre` pointer, to `null`. This means there is no address for
the next node, indicating that the node pointed to by `pre` is now the last node, as shown in the command and
image below.
-> insolo,
⑧ public boolean contains ( Object e ) ;
override
-
5 method p
Before creating a data structure using a Linked List, a node class is needed to create nodes to store
each data point. Since each node has two instance variables , ` data` and `next` , as explained above, this
class has four methods for `set` and ` get`. These two instance variables
ถึ
public class MyNode {
private Object data;
private MyNode next;
next = n;
}
data = d;
}
return next;
}
}
}
Next, create a bin using a Linked List and manage the data in this bin using the LinkedCollection
class below. This is a Collection data structure implemented using a Linked List ; therefore, this class will
handle the management of the data within it .
- Create an empty container in the class's constructor , setting `first = null;`.
- Enter the information into the Linked List.
Connect the data nodes using the `add` method . Or the `addEnd` method (add to the end).
By definition, data in a Collection does not have a specific order for storing or deleting data.
Therefore, when adding new data, it can be added to the beginning or to the end of a Linked List . Thus, the
LinkedCollection class below, which is the Collection data structure , only has the `add` method (for adding
data to the beginning) or the `addEnd` method (for adding data to the end) for adding new data.
- Deleting data from... Linked List by method remove ( Object o )
First, we need to find out which node the data 'o' is located in. This linked list uses a while loop to
move the 'start' pointer to the node containing the item to be deleted, and the 'pre' pointer to the node
preceding the ' start' pointer.
Then, upon leaving... If the while loop doesn't find a node containing the data (o) , it exits the remove
method using the keyword ` remove`. return However, if you encounter a node containing the data you want to
delete , check whether it is the first node of the linked list or a middle node. A linked list is the last node of a
list. Linked List: Then , once you know whether it's the first, middle , or last node , follow the deletion steps
described in Sections 5.1-5.3 of Section 2.1.2 above , respectively .
- Ask if the data specified in this Linked List exists , using the contain ( Object o ) method.
First, find out which node in the linked list contains the data 'o' using a while loop. The 'start' pointer
moves to the node containing the data you're looking for, similar to the ' remove' method 's while loop , but the
search doesn't require the 'pre' pointer. At the end of the while loop, the ' start' pointer points to the node
containing data 'o' (the node being searched). If the node containing data 'o' is not found, the 'start' pointer
moves to the end, reaching null (the 'next' part of the last node).
- Check if this data bin or linked list is empty using the isEmpty () method.
If the pointer ` first` doesn't point to any node, it means there's no data in this bucket; that is, `first =
null`.
- To find out how many entries are in this bin, or how many nodes are in this Linked List , use the
`size ()` method.
Return the variable ' size' , that is, return the variable ' size'.
- An additional method not included in the Collection ADT is the printlist() method . This method
displays the current contents of a linked list , from the first node to the last. It works by moving the pointer from
the start node to each node and printing the value of that node, continuing until the end of the linked list ( the
last node ).
public class LinkedCollection implements Collection{
ง mode
private MyNode first; & first (1 ข แรก
privateconuisize
=> int size; cos ***
↑
public LinkedCollection () { //Start at an empty bin
first = null; W ง เปล Link Lis
size = 0; } + แบ มน เ นแ บบ เ ยง
public boolean isEmpty () {
~
} firs ⑤
public int size () { -
return size; add ho's
⑤
nor
} add 3 add
add rew
* *
public void add ( Object value ) // Adding a node to·
the front
⑤
- - -
-
3)
125
{ * *
#units
Daniel
first = new MyNode ( value, first ) ;
size ++ ;
=
} #
S
start = [Link] ( ) ; ก
order first
I am /
#
}
} add ห ง
ง
public void addEnd ( Object obj ) //Adding a node to&
the end
%
{ if ( isEmpty ())
=
add ( obj ) ;
else { MyNode start = first;
ถึ
นี้
ตั
อั
ป็
ร้
ถั
ลั
รี
ว่
ปร
* จ:ป ล ันจ ะไป วท
น
int
↓
์ จะป
กกรณ
while (-
start . getNext () != null ) S! = ncl
System.
------
Out,
print (S.
get Date());
M
start = [Link] ();
<++ แ งใช้ size) <หงหนาด 8 3 nu
MyNode tmp = new MyNode ( obj, start . getNext () ) ;
#
* [Link] ( tmp ) ;
size ++ ;
Wor
}
}
public void remove ( Object o )
{
if ( isEmpty ()) // If there is no data, it cannot be removed .
return;
MyNode pre;
MyNode start = first;
while ( start . getNext () != null && !( start . getData (). equal ( o )))
{ pre = start;
start = [Link] ( ) ;
//Move the start line to the node containing the data to be deleted.
}
The test class below is used to test the LinkedCollection class , a data structure created using a
Linked List. It checks whether data is added, removed, whether the specified data exists, how many items are
in the collection, or whether the collection is empty. It checks if all of this works correctly .
public LinkedList () {
first = null;
size = 0;
}
public boolean isEmpty () {
return first == null; // size == 0;
}
public int size () {
return size;
}
public void printlist () // Traversing the list
{ MyNode start = first;
while ( start != null )
{
System . out . println ( start . getData () ) ;
start = [Link] ( ) ;
}
}
public void add ( Object obj ) //It's not possible to add a node from the back to the front because of the
order.
{
if ( isEmpty ())
first = new MyNode ( obj, first ) ;
else {
MyNode cur = first;
while ( cur . getNext () != null )
cur = [Link] ( ) ;
MyNode tmp = new MyNode ( obj, cur . getNext () ) ;
[Link] ( tmp ) ;
size ++ ;
}
}
// End else
size -- ;
}
}
I object data.
mode nex
&
class Linked
implement called
first = well;
#- + เ ย
todoy
นรวม
is Empty
Size
รี
#st เ ยงล
อย
ู
่ๆ จะเ อาเ ลขอะ
:: 4: มา แทรก ห
แทรก ห ง
5 P
ใ ้S chec
ขสเหต < ให
้
>เ อ นไปเร
ื
Create a node to store the value 2, then set the ` next` part of this new node to the address of the first
node, where the variable ` first` stores the value 2. The address is there; that is, this new node points to the
first node, which is the node that stores the value 3. Then, move the pointer " first" to point to the new node
instead by assigning a variable... First , store the address of the new node, which is node 2 . Address of node
3 That means this new node, which stores the value 2 , has become the first node of the Linked List.
#
M
1. setNextSt)
tsetnext ( +1
2. add. ( 3)
1. add ( 5) ;
·
2. Add /3)
รี
ลั
น้
ช้
ลื
ำ
public Void add ( Object &(
#
ก บมมาตรง
cal!"
if (s #
return
n
<return ไ ่ อ ะไรไ ใน ro i
My node -+ = new
My nodeld, null);
fron
thadd
if JS = = = first) * coccision add uw
if = = =
first()
&#
o to setNext
าเ น first ส
· t = +, 5 ส บ-
9. setNext ( +) ;
1. setNextSt)
t setnext ( +1
ซ้
ลั
ถ้
ด้
มี
ล้
มี
ลั
ม่
ป็
ลั
ม่
Since we need to know the position of the new value to be inserted beforehand, a while loop is
used to move the pointer continuously until it finds a node with a value greater than the data to be inserted (in
the case of sorting from smallest to largest as in the example). This pointer is named cur1 , and a pointer,
cur2, follows closely behind to stop before cur1.
Initially, set the pointers cur1 and cur2 to point to the first node, i.e., set cur1 and cur2 equal to `first`, as
shown in the command and image below.
Move the cur1 pointer to a node with a value greater than the data to be entered, then move the
cur2 pointer. Coming one after another. It stops at the node preceding the node pointed to by cur1 , as shown
in the image below, using... The two statements below should be inside a while loop. See the `add ( Object
value )` method in the LinkedSort class.
Next, create a new node and store the value 4. Set the `next` section of the node `cur2` to the
address of the new node (i.e., point to the new node). Then, set the ` next` section of the new node to the
address of the node `cur1` (i.e., point to the node that `cur1` points to). In other words, insert the node
between node `cur2` and node `cur1` as shown in the image below using the command below.
2.4.3 Adding a new node to the end of a linked list .
To add the number 8 to this list (or linked list) , since Sort sorts the data, the number 8 must be
appended to the end of the linked list.
Initially, the pointers cur1 and cur2 point to the first node, i.e., set cur1 and cur2 equal to `first` , which
stores the address of the first node, as shown in the figure and the two commands below.
Because the while loop in the `add ( Object value )` method of the LinkedSort class below contains
the statements `cur2 = cur1; cur1 = [Link] ( ) ; ` , which moves the pointer of `cur1` to a node with a
value greater than the data to be inserted, but in the case of appending to the end of a Linked List , the data
to be inserted will have a value greater than all other values in the Linked List. Therefore, the pointer of `cur1`
stops at `null` , which is the `next` part of the last node, while the pointer of `cur2` stops before ` cur1` , i.e. , at
the last node, as shown in the three figures below.
Create a new node and store 8. Then , set the `next` parameter to ` cur1` , which means it should be
null. Then, set the `next` value of the last node pointed to by the cur2 pointer to the address of the new node;
that is, point to the new node, thus adding the new node to the end of the Linked List according to the
command and the image below.
2.4.4 Implement Sort using a Singly Linked List .
It's time to create a data structure using a Linked List. First, we need the Abstract Data Type of Sort ,
which is the Sort interface and has four methods.
public interface Sort {
public void add ( Object e ) ;
public void remove ( Object e ) ;
public boolean contains ( Object e ) ;
public boolean isEmpty ( ) ;
}
Before creating a data structure using a Linked List , you need a node class to create nodes to store
each piece of data.
Because a singly linked list is used to create the data structure, Sort uses the MyNode class to create each
node as before.
Let's create a Sort data structure from the LinkedSort class below. Since it uses a singly linked list to
create data, like a Collection , most methods are implemented similarly, except for the add method, which
differs significantly between Sort and other data structures. And the Collection
- Starting with the constructor , which represents an empty data container, it has the same command as the
collection data structure : ` first = null ;`
- The `add ( Object value )` method differs because Collections can add data before or after the list, as long
as the data is added to the node. Sort, however , requires checking the index of the data to be added. For
example, if the list contains the 3, 8, 10, and 35 , adding 9 requires placing it between the nodes containing 8
and 10 ; it cannot be inserted before or after the list. Therefore, data added to a Sort node can be placed at
the very beginning, in the middle , or at the end of the linked list , as explained in sections 2.4.1-2.4.3 above .
- The method remove ( Object o ) is similar to The `remove` function of the `LinkedCollection` class is useful
because there are three ways to delete a node: the first node, the middle node, or the last node of the linked
list. The difference lies in how the pointer moves from `start` to the node containing the data to be deleted. In
a Collection , the data is not sorted, so you need to search for the data to be deleted from the first to the last
node of the linked list. In contrast, `sort` sorts the data in a given list. It's already a linked list. Therefore , if the
pointer moves from 'start' to a node with a value greater than the one to be deleted (if the data is sorted from
smallest to largest) and still doesn't find it, it means the desired item hasn't been found, so the pointer stops
moving. This means the search stops without needing to search to the last node. Linked List
- method The `contains ( Object o )` method in the `sort` data structure differs from the `contains` method of
the `collection` data structure only in how the pointer moves from ` start` to the desired node. When a node
with a value greater than the desired node is found (if the data is sorted from smallest to largest), the search
stops. This is the same reasoning as the `remove` method above.
- The `isEmpty ()` method is the same for both Collections and Sorts ; it simply checks if the `first` pointer
exists, even if there is no node to point to , or if `first = null` , meaning the collection is empty.
- An additional method not included in Sort ADT is the printlist() method . This method displays the current
contents of a linked list , from the first node to the last. It works by moving the pointer from the start node to
each node and printing the value of that node, repeating this process until the end of the linked list.
public void remove ( Object o ) { // Delete the node with the value o
if ( isEmpty ())
return;
else
System . out . println (" Remove Value : " + o ) ;
System . out . println (" Is " + ob2 + " in the List? " ) ;
boolean a = list . contains ( ob2 ) ;
System . out . println ( a ) ;
System . out . println (" Is " + ob7 + " in the List? " ) ;
boolean b = list . contains ( ob7 ) ;
System . out . println ( b ) ;
[Link] ( ob3 ) ;
[Link] ( ) ;
list . remove ( ob4 ) ;
[Link] ( ) ;
list . remove ( ob8 ) ;
[Link] ( ) ;
}
}
Chapter 4 trees
A tree is a data structure that stores individual data in nodes. The nodes are arranged like an inverted
tree, starting from the root and followed by children, down to the lowest node which has no children, called a
leaf. Trees have levels , starting from level 0 at the root , as shown in the diagram below.
The term "subtree" refers to both left and right subtrees. In the image above, the left subtree of node
1 is...
From the image above, the subtree to the right of node 1 is...
1713 4.1 Binary tree
A tree that can have a maximum of 2 offspring, meaning it has a 0, 1 , or 2 chance of producing offspring from
any node.
4.1.1 Tree nodes
A node consists of three parts:
- The data storage area is the top part of the image below.
- The area where the child's address is stored on the left, or the left pointer, is the bottom left part
of the image below.
- The area where the child's address is stored , or the right-hand pointer, is the bottom right corner
of the image below.
To create a tree node, you need a node class. The node class has three instance variables : data...
The `left` and `right` methods store the address of the left child node and the address of the right child node,
respectively. Therefore, there are 6 instance methods . Methods for retrieving data. ( Get ) and change the
new information. ( set ) on data , left pointer, and right pointer.
class
My Mode class BTNode
BTNode root,
private Object data; public Tree(){
root =
null; }
private BTNode left;
private BTNode right;
LV < Mr
1. The child on the left must have a value less than the parent node.
2. The child on the right must have a value greater than the parent node.
#while
if
Croot =Yu
%
retur
Because the child node on the right is not greater than the parent node. 5
6
4.2.1 Creating a Binary Search Tree public
void. Add ( Object d)
The process of creating a binary search tree. BTNode = new BTNode ( d, hull, null)
* อ>สร้างเป ็น No de
BTNode -+ = new
BENode ( 8, null, wull)
root = t
While ( S! = null
P= =
&
6 = 3.
getLett
·
else if / &> s. getData() (
· S= 3. gelRight (
"ี -
From the image above , since 10 is greater than 8 , it is connected as the right child of thereturn
node storing the
is = nuแล: )
value 8.
if Id > ↑. getData()) {
↑. set Left ( +'; }
From the image above , since 1 is less than 8 , it is connected as the left child of the node storing the value 8.
้ำ
ำ
ม่
ต้
From the image above, since 3 is less than 8 , the node traverses to the left of the node storing the
value 8. Upon encountering the node storing the value 1, it compares whether 3 is greater than or less than 1.
In reality, 3 is greater than 1 , so the node 3 is connected as a right child of the node storing the value 1.
From the image above, since 9 is greater than 8 , the node traverses to the right of the node storing
8. Upon encountering the node storing 10 , it compares whether 9 is greater than or less than 10. In reality, 9 ?
# recursive
is less than 10, so node 9 is connected to the left child of the node storing 10. public InO ( BTNode) {
" void
#23.59
if (r = = = null) return;
repetitionalStroke
Pure
a
els
10 8
root
no [Link]
Traversal
>
tree pre order
- ⑤ 3. 0.
P getData
Cr.
3. 0.
P getData
Cr.
A. # A % InO Cr.
get Right
-
In Order
InO Cr.
get Right
Pre
* A A
Pos A
5
&
A
roo
·
+
↑ Po
0
⑤
:Qing
9 10
3 ↓
1 A
#8 public int size (BT mode
r)
if Jr = = null) return #
1+ 1 + 1 = 3
8 1 3 2 10 9
else if Ir != null)
, \
· I size ( 8.
getleftll) +1 + size ( ro get Right());
-
/ ·
& ป
ดั
#
#
#
S
BTuodes=
·to
root ;
while ( S! = null)
#
%
if 12 < 6. getData 1)
1 2
S = so
getLeft 1); 3)
else if 12 > s
getData 1. Set Right (null)
5 = S.
getRight();
Piset left (null)
100 el s Ne = S. getData 11,
root = wel
& retur true
if ( S = = = root)
root = hell
/
}else if (paget Right 1) = = 3) {
9. Set Right ( hull);
public void
remove ( object a) 3 else { 1) ( pagetleft 1) == S
- ไห ht
tinal
Post
ก
- าไ ี I retur nไม
"
> ไม
4 ไ ปช
ี แม่
http
in
we want
ก
ก
ก
ก
& order
sirinSite ·SO
BTnodes : root
&
P= S
if /2 < getDatall)S.
3 = S. getleftl);
alse if
Je > s.
getDatall) ก if (S. getleft 1) != nell)
↓I
S = 3. get Right(); if ( S = = root
alse }
ไ
#k;
post .ent
!
-
if 28 = =
wull) {
/ไม
print "ไม่เจอ !ไ ง
return;
-check
·Prop setheft
(
ไ ม กทม
7 else 11 100
ก
! { if16:
=200
superh
else se
( posetRightssohtt
ase Pent
# sort -
↓
↑ yelse
มี
มี
ลู
ลู
ทีี่
ม่
ลู
มี
ลู
มี
ก็
ลู
มี
ซ้
ถ้
ม่
ลู
ทั้
ชี
3) 3
+- Dimax
left
-> าง: หา m
Lef
- get min, ma
roo
·
int size ( Thode 2)
if (2 = = null) return ·"
ese
⑤
14
max/ level ( rogetleft()))
level [Link]())
:50
↑
-root & 1#
&
2 3
5
· 1+ max#SO), (
-ร
↑
#
-I
It imall, #Mul
le
⑧ ·- I
เ อกต
ว
ที่
ตั
ลื
คื
ถ้
ถ้
From the image above , since 2 is less than 8 , the node traverses to the left of the node storing 8.
Upon encountering the node storing 1 , it compares whether 2 is greater than or less than 1. Since 2 is greater
than 1 , the node traverses to the right of node 1, reaching node 3. It compares again, and since 2 is less than
เร
From the image above , since 4 is less than 8 , the node traverses to the left of the node storing 8.
Upon encountering the node storing 1 , it compares whether 4 is greater than or less than 1. Since 4 is greater
than 1 , the node traverses to the right of node 1, reaching node 3. It compares again, and since 4 is greater
than 3 , it connects node 4 as a right child of the node storing 3.
From the image above , since 12 is greater than 8 , we traverse to the right of the node storing the
value 8. When we encounter the node storing the value 10 , we compare whether 12 is greater than or less
than 10. In reality, 12 is greater than 10, so we proceed to the node containing 12. Connect it as the right child
of the node that stores the value 10.
4.2.2 Deleting Nodes in a Binary Search Tree
Since a binary search tree has a maximum of 2 children , the node to be removed has a chance of
having 0 children, 1 child , or 2 children .
Case of deleting a node that has 0 children.
- If the node to be deleted is the root.
When a node is deleted, the root becomes null , meaning there are no nodes left on the tree, as shown in the
command and image below.
Delete by setting the left pointer of the parent to null ; that is, the parent will no longer have any children on its
left, as shown in the command and image below.
- If the node to be deleted is the right child of the parent.
Delete by setting the right pointer of the parent to null , meaning the parent will no longer have any children to
its right, as shown in the command and image below.
- If the node to be deleted is the root and has one child to its left.
Deleted by set. The root directory becomes the left-hand child of the directory you want to delete, as shown in
the command and image below.
- If the node to be deleted is the left child of the parent, but there is one child on the left side as
well.
To delete, set the left pointer of the parent node of the node to be deleted to the left child node of the node to
be deleted, as shown in the command and image below.
If the node to be deleted is the right child of the parent.
- If the node to be deleted is the right child of the parent, but there is one child on the right side of
that node.
To delete, set the right pointer of the parent node of the node to be deleted to the right child node of the node
to be deleted, as shown in the command and image below.
-
- If the node to be deleted is the right child of the parent, but there is one child on the left.
To delete, set the right pointer of the parent node of the node to be deleted to the left child node of the node
to be deleted, as shown in the command and image below.
If the node to be deleted has 2 children.
two ways to do it :
1. Select the node with the highest value that is less than the node you want to delete; that is, the
bottom right node of the left subtree of the node you want to delete.
2. Select the node with the smallest value that is greater than the node you want to delete; that is, the
bottom left node of the right subtree of the node you want to delete.
Once you have the node from step 1 or 2 , overwrite the value of the node you want to delete with the
value of one of those nodes. Then, delete the node obtained from step 1 or 2 .
Below is a demonstration of deletion using only method 1.
To delete a node that stores the value 31 and has two children , the following steps would be taken:
1. Select the node with the highest value that is less than the node you want to delete. This means
selecting the bottom right node of the left subtree of the node you want to delete; that is, the
node that stores the value 30.
2. the value in node 31 with the value 30.
3. Delete the original node that stored the value 30.
Move the `start` pointer to the node you want to delete, and the ` pre` pointer to the parent node of the node
you want to delete, as shown in the image below.
Set the pre2 pointer to the same location as the start pointer , and the cur pointer to the root of the left
subtree, as shown in the command and image below.
Then, move the cur pointer forward to the bottom right node, with the pre2 pointer following, as shown in the
command and image below.
Then, move the cur pointer towards the bottom right node, with the pre2 pointer following. As per the
instructions and image below.
cur pointer has now reached the largest node that is less than the node to be deleted, specifically the node
containing the value 30 , as shown in the command and image below.
Then, the value in the node pointed to by `cur` overwrites the value in the node `start` , which is the node
intended to be deleted, as shown in the command and image below.
Next, delete the original node that stored the value 30 by setting the right pointer of the parent node of node
30 , which is pointed to by the pre2 pointer, to... The address of the left child node of node 30 is shown in the
figure below. Because node 30 is the bottom right node, it cannot have a child to the right. As per the
instructions and image below.
Example 2 : Case where there is no bottom right node in the left subtree.
Set the pre2 pointer to the same location as the start pointer , and set the cur pointer to the root of the left
subtree, as shown in the image below.
Since there is no right node to the cur pointer, it means that the cur pointer stores the largest value in
the left subtree of the node to be deleted, which is the node that the start pointer is pointing to. Then, the value
in the node pointed to by cur overwrites the value in the node that starts , which is the node intended to be
deleted, as shown in the image below. That is, node 4 is overwritten with the value 2, as shown in the image
below.
Then, delete node 2 that the cur pointer is pointing to using the command. [Link] ( [Link] ( ) ) ;
results in the image below .
4.3 Tree traversal
There are 3 types .
1. Inorder means traversing to... Left subtree, Root, Right subtree, in that order.
2. Preorder means traversing the Root, Left subtree, and Right subtree in that order.
3. Postorder is a navigation tool that goes to... Left subtree, Right subtree, Root, in that order.
Example 1
Example 2
Example 3
Now let's create the data structure from the BinarySearchTree class below, using Binary Search Tree
to construct the data structure.
- Starting with the constructor , which represents an empty data container, the command is `root = null; `,
meaning there isn't even a root node.
- The `add ( Object e )` method adds a node with the value 'e' to the tree. First, we need to determine the
location of 'e' in the tree. The `while` loop within the `add` method handles this. The `start` pointer initially
points to the root and moves down until it finds the correct position. The `while` loop checks whether the
added value is greater than or less than the value of the node in the tree indicated by the ` start` pointer. If the
value at the node pointed to by 'pre' is greater than the value at the node pointed to by 'pre', the ' start ' pointer
moves to the right. If the value at the node pointed to by 'pre' is less than the value at the node pointed to by
'pre' , the new node will connect to it as a child. After exiting the while loop , only the node pointed to by 'pre'
is returned (the node the new node will connect to as a child). However, it's not yet clear whether the new
node will be a right or left child. Therefore, an 'if' statement is used to determine if the value at the node pointed
to by 'pre' is greater than or less than the new value being entered. If the new value is greater than the value
at the node pointed to by ' pre' , the new node will connect as a right child of the node pointed to by 'pre' .
Conversely, if the new value is less than the value at the node pointed to by 'pre' , the new node will connect
as a left child of the node pointed to by 'pre' .
- The `contains ( Object e )` method moves the `start` pointer to the desired node. It's similar to the `add`
method 's `while` loop , where the `start` pointer initially points to the root and moves down until it finds the
desired value. Within the `while` loop , it checks if the value of `e` is greater than or less than the value of the
node in the tree that the ` start` pointer is pointing to. If it's greater, the `start` pointer moves to the right; if it's
less, it moves to the left. If the ` start` pointer stops at `null` , it means the desired value wasn't found.
- The `isEmpty ()` method checks if the root pointer contains no nodes to point to, or if ` root = null` means the
container is empty.
- The `printTree()` method is used to display the current data in the tree from the first node to the last node.
This method prints the value of each node in three ways, depending on tree traversal : Preorder, InOrder, or
PostOrder.
- The getMin () method returns the smallest value in the tree by having the start pointer navigate to the bottom
left node of the tree, which is the node with the smallest value.
The getMax () method returns the largest value in the tree by having the start pointer navigate to the bottom
right node of the tree, which is the node with the largest value.
-rop
size = 0;
-print
For
}
curtai
}
}
return false; // No data found
}
if ( root == null ) { // If the bin is empty, any new node entering will immediately become the root of the tree.
root = tmp;
size ++ ;
}
else{
while ( start != null ) {
pre = start;
int BTNode = ( Integer ) start . getData ( ) ;
if ( BTNode == value ) {
System . out . println (" Object : " + e +" has existed in the tree ." ) ;
start = null;
return;
}
else{
if ( BTNode > value )
start = [Link] ( ) ;
else
start = start . getRight ( ) ;
}
// When the while loop ends This will create the parent node of the new node, which will have a `pre` pointer
pointing to it.
int curNode = ( Integer ) pre . getData ( ) ;
if ( curNode > value ) { // If the new node has a value less than the node that pre points to, the new node
becomes the left child.
[Link] ( tmp ) ;
size ++ ;
}
else if ( curNode < value ) { // If the new node has a value greater than the pre -curNode } The indicator points
the new node to be its right child.
[Link] ( tmp ) ;
size ++ ;
}
}
} // end of Method ddd
Output
run :
Preorder
9 2 1 5 12 10 15
Inorder
1 2 5 9 10 12 15
Postorder
1 5 2 10 15 12 9
Size : 7
Min : 1
Max : 15
Is 12 in the tree? True
Is 20 in the tree? False
[Link] ( ob1 ) ;
[Link] ( ob2 ) ;
[Link] ( ob3 ) ;
[Link] ( ob4 ) ;
[Link] ( ob5 ) ;
[Link] ( ob6 ) ;
[Link] ( ob7 ) ;
BST . printTree () ;
System . out . println (" Size : " + BST . size ()) ;
System . out . println (" Min : " + BST . getMin ()) ;
System . out . println (" Max : " + BST . getMax ()) ;
System . out . println (" Is " + ob3 + " in the tree? " + " \t " + BST . contains ( ob3 )) ;
System . out . println (" Is " + ob8 + " in the tree? " + " \t " + BST . contains ( ob8 )) ;
}
}
Output
run :
Preorder
9 2 1 5 12 10 15
Inorder
1 2 5 9 10 12 15
Postorder
1 5 2 10 15 12 9
Size : 7
Min : 1
Max : 15
Is 12 in the tree? True
Is 20 in the tree? False