SlideShare a Scribd company logo
1 of 12
TRƯỜNG ĐẠI HỌC BÁCH KHOA HÀ NỘI 
VIỆN CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG 
BÀI TẬP LỚN 
Algorithm Computer 
BÀI TẬP LỚN MÔN HỌC 
IT3053 Tiếng Anh CN CNTT 
Giáo Viên: Nguyễn Thanh Hùng 
Sinh viên: Nguyễn Bá Cương 
MSSV: 20121352 
Lớp: KSTN-CNTT-K57 
HÀ NỘI 2014 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 1
Contents 
..........................................................................................................................................................1 
Tree Terminology ...............................................................................................................................3 
Algonrithm for the Tree. .....................................................................................................................6 
 The Node Class ........................................................................................................................6 
 The Tree Class .........................................................................................................................6 
Finding a Node ...................................................................................................................................6 
 Using the Workshop Applet to Find a Node ...............................................................................7 
 Code for Finding a Node...........................................................................................................9 
 Can’t Find the Node .............................................................................................................9 
 Found the Node ...................................................................................................................9 
Inserting a Node ............................................................................................................................... 10 
 Using the Workshop Applet to Insert a Node........................................................................... 10 
 Code for Inserting a Node ...................................................................................................... 11 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 2
Tree Terminology 
Many terms are used to describe particular aspects of trees. You need to know a few of 
them so our discussion will be comprehensible. Fortunately, most of these terms are 
related to real-world trees or to family relationships (as in parents and children), so 
they’re not hard to remember.Figure 1.1 shows many of these terms applied to a 
binary tree. 
Figure 1.1 
 Path 
Think of someone walking from node to node along the edges that connect them. 
The resulting sequence of nodes is called a path. 
 Root 
The node at the top of the tree is called the root. There is only one root in a tree. 
For a collection of nodes and edges to be defined as a tree, there must be one (and 
only one!) path from the root to any other node. Figure 1.2 shows a non-tree. You 
can see that it violates this rule. 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 3
Figure 1.2 
 Child 
Any node may have one or more lines running downward to other nodes. These 
nodes below a given node are called its children. 
 Leaf 
A node that has no children is called a leaf node or simply a leaf. 
There can be only one root in a tree, but there can be many leaves. 
 Subtree 
Any node may be considered to be the root of a subtree, which consists of its 
children, and its children’s children, and so on. If you think in terms of families, a 
node’s subtree contains all its descendants. 
 Visiting 
A node is visited when program control arrives at the node, usually for the 
purpose of carrying out some operation on the node, such as checking the value of 
one of its data fields or displaying it. Merely passing over a node on the path from 
one node to another is not considered to be visiting the node. 
 Traversing 
To traverse a tree means to visit all the nodes in some specified order. For 
example, you might visit all the nodes in order of ascending key value. There are 
other ways to traverse a tree, as we’ll see later. 
 Levels 
The level of a particular node refers to how many generations the node is from the 
root. If we assume the root is Level 0, then its children will be Level 1, its 
grandchildren will be Level 2, and so on. 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 4
 Keys 
We’ve seen that one data field in an object is usually designated a key value. This 
value is used to search for the item or perform other operations on it. In tree 
diagrams, when a circle represents a node holding a data item, the key value of 
the item is typically shown in the circle. (We’ll see many figures later on that 
show nodes containing keys.) If every node in a tree can have at most two 
children, the tree is called a binary tree. In this chapter we’ll focus on binary trees 
because they are the simplest and the most common. The two children of each 
node in a binary tree are called the left child and the right child, corresponding to 
their positions when you draw a picture of a tree, as shown in Figure 1.1. A node 
in a binary tree doesn’t necessarily have the maximum of two children; it may 
have only a left child, or only a right child, or it can have no children at all (in 
which case it’s a leaf). The kind of binary tree we’ll be dealing with in this 
discussion is technically called a binary search tree. Figure 1.3 shows a binary 
search tree. 
FIGURE 1.3 A binary search tree. 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 5
Algonrithm for the Tree. 
 The Node Class 
First, we need a class of node objects. These objects contain the data representing 
the objects being stored (employees in an employee database, for example) and 
also references to each of the node’s two children. Here’s how that looks: 
class Node 
{ 
int iData; // data used as key value 
double fData; // other data 
node leftChild; // this node’s left child 
node rightChild; // this node’s right child 
} 
 The Tree Class 
We’ll also need a class from which to instantiate the tree itself: the object that 
holds all the nodes. We’ll call this class Tree. It has only one field: a Node 
variable that holds the root. It doesn’t need fields for the other nodes because they 
are all accessed from the root. The Tree class has a number of methods. They are 
used for finding, inserting, and deleting nodes; for different kinds of traverses; 
and for displaying the tree. Here’s a skeleton version: 
class Tree 
{ 
private Node root; // the only data field in Tree 
public void find(int key){ 
} 
public void insert(int id, double dd){ 
} 
public void delete(int id){ 
} 
// various other methods 
} // end class Tree 
Finding a Node 
 Finding a node with a specific key is the simplest of the major tree operations, so 
let’s start with that. 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 6
Remember that the nodes in a binary search tree correspond to objects containing 
information. They could be person objects, with an employee number as the key 
and 
also perhaps name, address, telephone number, salary, and other fields. Or they 
could represent car parts, with a part number as the key value and fields for 
quantity on hand, price, and so on. However, the only characteristics of each 
node that we see in the Workshop applet are a number and a color. A node is 
created with these two characteristics, and keeps them throughout its life. 
 Using the Workshop Applet to Find a Node 
Look at the Workshop applet, and pick a node, preferably one near the bottom of 
the tree (as far from the root as possible). The number shown in this node is its key 
value. We’re going to demonstrate how the Workshop applet finds the node, given 
the key value. 
For purposes of this discussion we’ll assume you’ve decided to find the node 
representing the item with key value 57, as shown in Figure 8.7. Of course, when 
you run the Workshop applet, you’ll get a different tree and will need to pick a 
different key value. 
Click the Find button. The prompt will ask for the value of the node to find. Enter 57 
(or whatever the number is on the node you chose). Click Find twice more. 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 7
FIGURE 1.4 Finding node 57. 
As the Workshop applet looks for the specified node, the prompt will display 
either Going to left child or Going to right child, and the red arrow will move down 
one level to the right or left 
In Figure 1.4 the arrow starts at the root. The program compares the key value 57 
with the value at the root, which is 63. The key is less, so the program knows the 
desired node must be on the left side of the tree—either the root’s left child or one of 
this child’s descendants. The left child of the root has the value 27, so the 
comparison of 57 and 27 will show that the desired node is in the right subtree of 27. 
The arrow will go to 51, the root of this subtree. Here, 57 is again greater than the 51 
node, so we go to the right, to 58, and then to the left, to 57. This time the 
comparison shows 57 equals the node’s key value, so we’ve found the node we want. 
The Workshop applet doesn’t do anything with the node after finding it, except to 
display a message saying it has been found. A serious program would perform some 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 8
operation on the found node, such as displaying its contents or changing one of its 
fields. 
 Code for Finding a Node 
Here’s the code for the find() routine, which is a method of the Tree class: 
public Node find(int key) // find node with given key 
{ // (assumes non-empty tree) 
Node current = root; // start at root 
while(current.iData != key) // while no match, 
{ 
if(key < current.iData) // go left? 
current = current.leftChild; 
else 
current = current.rightChild; // or go right? 
if(current == null) // if no child, 
return null; // didn’t find it 
} 
return current; // found it 
} 
This routine uses a variable current to hold the node it is currently examining. The 
argument key is the value to be found. The routine starts at the root. (It has to; this is the 
only node it can access directly.) That is, it sets current to the root. 
Then, in the while loop, it compares the value to be found, key, with the value of the 
iData field (the key field) in the current node. If key is less than this field, current is set to 
the node’s left child. If key is greater than (or equal) to the node’s iData field, current is 
set to the node’s right child. 
 Can’t Find the Node 
If current becomes equal to null, we couldn’t find the next child node in the sequence; 
we’ve reached the end of the line without finding the node we were looking. 
 Found the Node 
If the condition of the while loop is not satisfied, so that we exit from the bottom of the 
loop, the iData field of current is equal to key; that is, we’ve found the node we want. We 
return the node so that the routine that called find() can access any of the node’s data. 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 9
Inserting a Node 
 To insert a node, we must first find the place to insert it. This is much the same 
process as trying to find a node that turns out not to exist, as described in the 
“Can’t Find the Node” section. We follow the path from the root to the 
appropriate node, which will be the parent of the new node. When this parent is 
found, the new node is connected as its left or right child, depending on whether 
the new node’s key is less or greater than that of the parent. 
 Using the Workshop Applet to Insert a Node 
To insert a new node with the Workshop applet, press the Ins button. You’ll be 
asked to type the key value of the node to be inserted. Let’s assume we’re going 
to insert a new node with the value 45. Type this number into the text field. 
The first step for the program in inserting a node is to find where it should be 
inserted. Figure 1.5 a shows how this step looks. 
FIGURE 1.5 Inserting a node. 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 10
The value 45 is less than 60 but greater than 40, so we arrive at node 50. Now we 
want to go left because 45 is less than 50, but 50 has no left child; its leftChild 
field is null. When it sees this null, the insertion routine has found the place to 
attach the new node. The Workshop applet does this by creating a new node with 
the value 45 (and a randomly generated color) and connecting it as the left child 
of 50, as shown in Figure 1.5 b. 
 Code for Inserting a Node 
The insert() function starts by creating the new node, using the data supplied as 
arguments. 
Next, insert() must determine where to insert the new node. This is done using 
roughly the same code as finding a node, described in the section “Java Code for 
Finding a Node.” The difference is that when you’re simply trying to find a node 
and you encounter a null (non-existent) node, you know the node you’re looking 
for doesn’t exist so you return immediately. When you’re trying to insert a node, 
you insert it (creating it first, if necessary) before returning. 
The value to be searched for is the data item passed in the argument id. The while 
loop uses true as its condition because it doesn’t care if it encounters a node with 
the same value as id; it treats another node with the same key value as if it were 
simply greater than the key value. 
A place to insert a new node will always be found (unless you run out of 
memory); when it is, and the new node is attached, the while loop exits with a 
return statement. 
Here’s the code for the insert() function: 
public void insert(int id, double dd) 
{ 
Node newNode = new Node(); // make new node 
newNode.iData = id; // insert data 
newNode.dData = dd; 
if(root==null) // no node in root 
root = newNode; 
else // root occupied 
{ 
Node current = root; // start at root 
Node parent; 
while(true) // (exits internally) 
{ 
parent = current; 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 11
if(id < current.iData) // go left? 
{ 
current = current.leftChild; 
if(current == null) // if end of the line, 
{ // insert on left 
parent.leftChild = newNode; 
return; 
} 
} // end if go left 
else // or go right? 
{ 
current = current.rightChild; 
if(current == null) // if end of the line 
{ // insert on right 
parent.rightChild = newNode; 
return; 
} 
} // end else go right 
} // end while 
} // end else not root 
} // end insert() 
// ------------------------------------------------------------- 
We use a new variable, parent (the parent of current), to remember the last non-null 
node we encountered (50 in Figure 8.8). This is necessary because current is 
set to null in the process of discovering that its previous value did not have an 
appropriate child. If we didn’t save parent, we would lose track of where we were. 
To insert the new node, change the appropriate child pointer in parent (the last 
nonnull node you encountered) to point to the new node. If you were looking 
unsuccessfully for parent’s left child, you attach the new node as parent’s left 
child; if you were looking for its right child, you attach the new node as its right 
child. In Figure 1.5, 45 is attached as the left child of 50. 
Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 12

More Related Content

Similar to Bao cao

Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanDaniyal Khan
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationnakulvarshney371
 
Part 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docxPart 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docxherbertwilson5999
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptxskilljiolms
 
Binary Tree - Algorithms
Binary Tree - Algorithms Binary Tree - Algorithms
Binary Tree - Algorithms CourseHunt
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docxsowmya koneru
 
Chapter 8: tree data structure
Chapter 8:  tree data structureChapter 8:  tree data structure
Chapter 8: tree data structureMahmoud Alfarra
 
Tree data structure in java
Tree data structure in javaTree data structure in java
Tree data structure in javaIrfan CH
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeZafar Ayub
 
DATA STUCTURES-TREES.pptx
DATA STUCTURES-TREES.pptxDATA STUCTURES-TREES.pptx
DATA STUCTURES-TREES.pptxAryaMNair6
 
Trees in data structures
Trees in data structuresTrees in data structures
Trees in data structuresASairamSairam1
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxRajitha Reddy Alugati
 

Similar to Bao cao (20)

Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
 
Part 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docxPart 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docx
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Binary Tree - Algorithms
Binary Tree - Algorithms Binary Tree - Algorithms
Binary Tree - Algorithms
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
 
Chapter 8: tree data structure
Chapter 8:  tree data structureChapter 8:  tree data structure
Chapter 8: tree data structure
 
Tree data structure in java
Tree data structure in javaTree data structure in java
Tree data structure in java
 
Unit iv data structure-converted
Unit  iv data structure-convertedUnit  iv data structure-converted
Unit iv data structure-converted
 
Tree data structure
Tree data structureTree data structure
Tree data structure
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Binary tree
Binary  treeBinary  tree
Binary tree
 
AD3251-Data Structures Design-Notes-Tree.pdf
AD3251-Data Structures  Design-Notes-Tree.pdfAD3251-Data Structures  Design-Notes-Tree.pdf
AD3251-Data Structures Design-Notes-Tree.pdf
 
DATA STUCTURES-TREES.pptx
DATA STUCTURES-TREES.pptxDATA STUCTURES-TREES.pptx
DATA STUCTURES-TREES.pptx
 
Trees in data structures
Trees in data structuresTrees in data structures
Trees in data structures
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
 

More from Cương Nguyễn Bá

More from Cương Nguyễn Bá (9)

50 bai hoc_tieng_nhat_ban_nhk
50 bai hoc_tieng_nhat_ban_nhk50 bai hoc_tieng_nhat_ban_nhk
50 bai hoc_tieng_nhat_ban_nhk
 
Textbook english
Textbook englishTextbook english
Textbook english
 
Rajesh
RajeshRajesh
Rajesh
 
Get certificate course_id=973756
Get certificate course_id=973756Get certificate course_id=973756
Get certificate course_id=973756
 
Hoan thien_he_thong_kenh_phan_phoi_sp_cua_cty_gach_op_lat_ha_noi_1101
 Hoan thien_he_thong_kenh_phan_phoi_sp_cua_cty_gach_op_lat_ha_noi_1101 Hoan thien_he_thong_kenh_phan_phoi_sp_cua_cty_gach_op_lat_ha_noi_1101
Hoan thien_he_thong_kenh_phan_phoi_sp_cua_cty_gach_op_lat_ha_noi_1101
 
Vasudevan columbia 0054_d_10779
Vasudevan columbia 0054_d_10779Vasudevan columbia 0054_d_10779
Vasudevan columbia 0054_d_10779
 
200 bai tap_vl8_2127
200 bai tap_vl8_2127200 bai tap_vl8_2127
200 bai tap_vl8_2127
 
1320 126
1320 1261320 126
1320 126
 
Cửa phòng có 5 cửa
Cửa phòng có 5 cửaCửa phòng có 5 cửa
Cửa phòng có 5 cửa
 

Recently uploaded

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Bao cao

  • 1. TRƯỜNG ĐẠI HỌC BÁCH KHOA HÀ NỘI VIỆN CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG BÀI TẬP LỚN Algorithm Computer BÀI TẬP LỚN MÔN HỌC IT3053 Tiếng Anh CN CNTT Giáo Viên: Nguyễn Thanh Hùng Sinh viên: Nguyễn Bá Cương MSSV: 20121352 Lớp: KSTN-CNTT-K57 HÀ NỘI 2014 Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 1
  • 2. Contents ..........................................................................................................................................................1 Tree Terminology ...............................................................................................................................3 Algonrithm for the Tree. .....................................................................................................................6  The Node Class ........................................................................................................................6  The Tree Class .........................................................................................................................6 Finding a Node ...................................................................................................................................6  Using the Workshop Applet to Find a Node ...............................................................................7  Code for Finding a Node...........................................................................................................9  Can’t Find the Node .............................................................................................................9  Found the Node ...................................................................................................................9 Inserting a Node ............................................................................................................................... 10  Using the Workshop Applet to Insert a Node........................................................................... 10  Code for Inserting a Node ...................................................................................................... 11 Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 2
  • 3. Tree Terminology Many terms are used to describe particular aspects of trees. You need to know a few of them so our discussion will be comprehensible. Fortunately, most of these terms are related to real-world trees or to family relationships (as in parents and children), so they’re not hard to remember.Figure 1.1 shows many of these terms applied to a binary tree. Figure 1.1  Path Think of someone walking from node to node along the edges that connect them. The resulting sequence of nodes is called a path.  Root The node at the top of the tree is called the root. There is only one root in a tree. For a collection of nodes and edges to be defined as a tree, there must be one (and only one!) path from the root to any other node. Figure 1.2 shows a non-tree. You can see that it violates this rule. Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 3
  • 4. Figure 1.2  Child Any node may have one or more lines running downward to other nodes. These nodes below a given node are called its children.  Leaf A node that has no children is called a leaf node or simply a leaf. There can be only one root in a tree, but there can be many leaves.  Subtree Any node may be considered to be the root of a subtree, which consists of its children, and its children’s children, and so on. If you think in terms of families, a node’s subtree contains all its descendants.  Visiting A node is visited when program control arrives at the node, usually for the purpose of carrying out some operation on the node, such as checking the value of one of its data fields or displaying it. Merely passing over a node on the path from one node to another is not considered to be visiting the node.  Traversing To traverse a tree means to visit all the nodes in some specified order. For example, you might visit all the nodes in order of ascending key value. There are other ways to traverse a tree, as we’ll see later.  Levels The level of a particular node refers to how many generations the node is from the root. If we assume the root is Level 0, then its children will be Level 1, its grandchildren will be Level 2, and so on. Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 4
  • 5.  Keys We’ve seen that one data field in an object is usually designated a key value. This value is used to search for the item or perform other operations on it. In tree diagrams, when a circle represents a node holding a data item, the key value of the item is typically shown in the circle. (We’ll see many figures later on that show nodes containing keys.) If every node in a tree can have at most two children, the tree is called a binary tree. In this chapter we’ll focus on binary trees because they are the simplest and the most common. The two children of each node in a binary tree are called the left child and the right child, corresponding to their positions when you draw a picture of a tree, as shown in Figure 1.1. A node in a binary tree doesn’t necessarily have the maximum of two children; it may have only a left child, or only a right child, or it can have no children at all (in which case it’s a leaf). The kind of binary tree we’ll be dealing with in this discussion is technically called a binary search tree. Figure 1.3 shows a binary search tree. FIGURE 1.3 A binary search tree. Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 5
  • 6. Algonrithm for the Tree.  The Node Class First, we need a class of node objects. These objects contain the data representing the objects being stored (employees in an employee database, for example) and also references to each of the node’s two children. Here’s how that looks: class Node { int iData; // data used as key value double fData; // other data node leftChild; // this node’s left child node rightChild; // this node’s right child }  The Tree Class We’ll also need a class from which to instantiate the tree itself: the object that holds all the nodes. We’ll call this class Tree. It has only one field: a Node variable that holds the root. It doesn’t need fields for the other nodes because they are all accessed from the root. The Tree class has a number of methods. They are used for finding, inserting, and deleting nodes; for different kinds of traverses; and for displaying the tree. Here’s a skeleton version: class Tree { private Node root; // the only data field in Tree public void find(int key){ } public void insert(int id, double dd){ } public void delete(int id){ } // various other methods } // end class Tree Finding a Node  Finding a node with a specific key is the simplest of the major tree operations, so let’s start with that. Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 6
  • 7. Remember that the nodes in a binary search tree correspond to objects containing information. They could be person objects, with an employee number as the key and also perhaps name, address, telephone number, salary, and other fields. Or they could represent car parts, with a part number as the key value and fields for quantity on hand, price, and so on. However, the only characteristics of each node that we see in the Workshop applet are a number and a color. A node is created with these two characteristics, and keeps them throughout its life.  Using the Workshop Applet to Find a Node Look at the Workshop applet, and pick a node, preferably one near the bottom of the tree (as far from the root as possible). The number shown in this node is its key value. We’re going to demonstrate how the Workshop applet finds the node, given the key value. For purposes of this discussion we’ll assume you’ve decided to find the node representing the item with key value 57, as shown in Figure 8.7. Of course, when you run the Workshop applet, you’ll get a different tree and will need to pick a different key value. Click the Find button. The prompt will ask for the value of the node to find. Enter 57 (or whatever the number is on the node you chose). Click Find twice more. Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 7
  • 8. FIGURE 1.4 Finding node 57. As the Workshop applet looks for the specified node, the prompt will display either Going to left child or Going to right child, and the red arrow will move down one level to the right or left In Figure 1.4 the arrow starts at the root. The program compares the key value 57 with the value at the root, which is 63. The key is less, so the program knows the desired node must be on the left side of the tree—either the root’s left child or one of this child’s descendants. The left child of the root has the value 27, so the comparison of 57 and 27 will show that the desired node is in the right subtree of 27. The arrow will go to 51, the root of this subtree. Here, 57 is again greater than the 51 node, so we go to the right, to 58, and then to the left, to 57. This time the comparison shows 57 equals the node’s key value, so we’ve found the node we want. The Workshop applet doesn’t do anything with the node after finding it, except to display a message saying it has been found. A serious program would perform some Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 8
  • 9. operation on the found node, such as displaying its contents or changing one of its fields.  Code for Finding a Node Here’s the code for the find() routine, which is a method of the Tree class: public Node find(int key) // find node with given key { // (assumes non-empty tree) Node current = root; // start at root while(current.iData != key) // while no match, { if(key < current.iData) // go left? current = current.leftChild; else current = current.rightChild; // or go right? if(current == null) // if no child, return null; // didn’t find it } return current; // found it } This routine uses a variable current to hold the node it is currently examining. The argument key is the value to be found. The routine starts at the root. (It has to; this is the only node it can access directly.) That is, it sets current to the root. Then, in the while loop, it compares the value to be found, key, with the value of the iData field (the key field) in the current node. If key is less than this field, current is set to the node’s left child. If key is greater than (or equal) to the node’s iData field, current is set to the node’s right child.  Can’t Find the Node If current becomes equal to null, we couldn’t find the next child node in the sequence; we’ve reached the end of the line without finding the node we were looking.  Found the Node If the condition of the while loop is not satisfied, so that we exit from the bottom of the loop, the iData field of current is equal to key; that is, we’ve found the node we want. We return the node so that the routine that called find() can access any of the node’s data. Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 9
  • 10. Inserting a Node  To insert a node, we must first find the place to insert it. This is much the same process as trying to find a node that turns out not to exist, as described in the “Can’t Find the Node” section. We follow the path from the root to the appropriate node, which will be the parent of the new node. When this parent is found, the new node is connected as its left or right child, depending on whether the new node’s key is less or greater than that of the parent.  Using the Workshop Applet to Insert a Node To insert a new node with the Workshop applet, press the Ins button. You’ll be asked to type the key value of the node to be inserted. Let’s assume we’re going to insert a new node with the value 45. Type this number into the text field. The first step for the program in inserting a node is to find where it should be inserted. Figure 1.5 a shows how this step looks. FIGURE 1.5 Inserting a node. Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 10
  • 11. The value 45 is less than 60 but greater than 40, so we arrive at node 50. Now we want to go left because 45 is less than 50, but 50 has no left child; its leftChild field is null. When it sees this null, the insertion routine has found the place to attach the new node. The Workshop applet does this by creating a new node with the value 45 (and a randomly generated color) and connecting it as the left child of 50, as shown in Figure 1.5 b.  Code for Inserting a Node The insert() function starts by creating the new node, using the data supplied as arguments. Next, insert() must determine where to insert the new node. This is done using roughly the same code as finding a node, described in the section “Java Code for Finding a Node.” The difference is that when you’re simply trying to find a node and you encounter a null (non-existent) node, you know the node you’re looking for doesn’t exist so you return immediately. When you’re trying to insert a node, you insert it (creating it first, if necessary) before returning. The value to be searched for is the data item passed in the argument id. The while loop uses true as its condition because it doesn’t care if it encounters a node with the same value as id; it treats another node with the same key value as if it were simply greater than the key value. A place to insert a new node will always be found (unless you run out of memory); when it is, and the new node is attached, the while loop exits with a return statement. Here’s the code for the insert() function: public void insert(int id, double dd) { Node newNode = new Node(); // make new node newNode.iData = id; // insert data newNode.dData = dd; if(root==null) // no node in root root = newNode; else // root occupied { Node current = root; // start at root Node parent; while(true) // (exits internally) { parent = current; Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 11
  • 12. if(id < current.iData) // go left? { current = current.leftChild; if(current == null) // if end of the line, { // insert on left parent.leftChild = newNode; return; } } // end if go left else // or go right? { current = current.rightChild; if(current == null) // if end of the line { // insert on right parent.rightChild = newNode; return; } } // end else go right } // end while } // end else not root } // end insert() // ------------------------------------------------------------- We use a new variable, parent (the parent of current), to remember the last non-null node we encountered (50 in Figure 8.8). This is necessary because current is set to null in the process of discovering that its previous value did not have an appropriate child. If we didn’t save parent, we would lose track of where we were. To insert the new node, change the appropriate child pointer in parent (the last nonnull node you encountered) to point to the new node. If you were looking unsuccessfully for parent’s left child, you attach the new node as parent’s left child; if you were looking for its right child, you attach the new node as its right child. In Figure 1.5, 45 is attached as the left child of 50. Nhóm : Nguyễn Thanh Hải – Phạm Tiến Dũng – Nguyễn Bá Cương Page 12