Chapter 20 Lists, Stacks, Queues, Trees, and Heaps Chapter 11 Object-Oriented Design Chapter 20 Lists, Stacks, Queues, Trees, and Heaps Chapter 21 Generics Chapter 22
Download ReportTranscript Chapter 20 Lists, Stacks, Queues, Trees, and Heaps Chapter 11 Object-Oriented Design Chapter 20 Lists, Stacks, Queues, Trees, and Heaps Chapter 21 Generics Chapter 22
Chapter 20 Lists, Stacks, Queues, Trees,
and Heaps
Chapter 11 Object-Oriented Design
Chapter 20 Lists, Stacks, Queues, Trees, and Heaps
Chapter 21 Generics
Chapter 22 Java Collections Framework
Chapter 19 Recursion
Chapter 23 Algorithm Efficiency and Sorting
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
1
Objectives
To describe what a data structure is (§20.1).
To explain the limitations of arrays (§20.1).
To implement a dynamic list using an array (§20.2.1).
To implement a dynamic list using a linked structure
(§20.2.2 Optional).
To implement a stack using an array list (§20.3).
To implement a queue using a linked list (§20.3).
To implement a binary search tree (§20.4).
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
2
What is a Data Structure?
A data structure is a collection of data organized in
some fashion. A data structure not only stores data,
but also supports the operations for manipulating
data in the structure. For example, an array is a data
structure that holds a collection of data in sequential
order. You can find the size of the array, store,
retrieve, and modify data in the array.
Array is simple and easy to use, but it has two
limitations:
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
3
Limitations of arrays
Once an array is created, its size cannot
be altered.
Array provides inadequate support for
inserting, deleting, sorting, and searching
operations.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
4
Object-Oriented Data Structure
In object-oriented thinking, a data structure is an object
that stores other objects, referred to as data or elements. So
some people refer a data structure as a container object or
a collection object. To define a data structure is essentially
to declare a class. The class for a data structure should use
data fields to store data and provide methods to support
operations such as insertion and deletion. To create a data
structure is therefore to create an instance from the class.
You can then apply the methods on the instance to
manipulate the data structure such as inserting an element
to the data structure or deleting an element from the data
structure.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
5
Four Classic Data Structures
Four classic dynamic data structures to be introduced in
this chapter are lists, stacks, queues, and binary trees. A list
is a collection of data stored sequentially. It supports
insertion and deletion anywhere in the list. A stack can be
perceived as a special type of the list where insertions and
deletions take place only at the one end, referred to as the
top of a stack. A queue represents a waiting list, where
insertions take place at the back (also referred to as the tail
of) of a queue and deletions take place from the front (also
referred to as the head of) of a queue. A binary tree is a data
structure to support searching, sorting, inserting, and
deleting data efficiently.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
6
Lists
A list is a popular data structure to store data in sequential
order. For example, a list of students, a list of available
rooms, a list of cities, and a list of books, etc. can be stored
using lists. The common operations on a list are usually the
following:
·
Retrieve an element from this list.
·
Insert a new element to this list.
·
Delete an element from this list.
·
Find how many elements are in this list.
·
Find if an element is in this list.
·
Find if this list is empty.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
7
Two Ways to Implement Lists
There are two ways to implement a list. One is to
use an array to store the elements. The array is
dynamically created. If the capacity of the array is
exceeded, create a new larger array and copy all the
elements from the current array to the new array.
The other approach is to use a linked structure. A
linked structure consists of nodes. Each node is
dynamically created to hold an element. All the
nodes are linked together to form a list.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
8
Design of ArrayList and LinkedList
For convenience, let’s name these two classes: MyArrayList and
MyLinkedList. These two classes have common operations, but
different data fields. The common operations can be generalized in an
interface or an abstract class. A good strategy is to combine the
virtues of interfaces and abstract classes by providing both interface
and abstract class in the design so the user can use either the interface
or the abstract class whichever is convenient. Such an abstract class is
known as a convenience class.
MyArrayList
MyList
MyAbstractList
MyLinkedList
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
9
MyList Interface and MyAbstractList Class
MyList
+add(o: Object) : void
Appends a new element o at the end of this list.
+add(index: int, o: Object) : void
Adds a new element o at the specified index in this list.
+clear(): void
Removes the element o from this list.
+contains(o: Object): boolean
Returns true if this list contains the element o.
+get(index: int) : Object
Returns the element from this list at the specified index.
+indexOf(o: Object) : int
Returns the index of the first matching element in this list.
+isEmpty(): boolean
Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int
Returns the index of the last matching element in this list.
+remove(o: Object): boolean
Removes all the elements from this list.
+size(): int
Returns the number of elements in this list.
+remove(index: int) : Object
Removes the element at the specified index.
+set(index: int, o: Object) : Object
Sets the element at the specified index.
MyAbstractList
#size: int
The size of the list.
#MyAbstractList()
Creates a default list.
#MyAbstractList(objects: Object[])
Creates a list from an array of objects.
+add(o: Object) : void
Implements the add method.
+isEmpty(): boolean
Implements the isEmpty method.
+size(): int
Implements the size method.
+remove(o: Object): boolean
MyList
MyAbstractList
Implements the remove method.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
10
Array Lists
Array is a fixed-size data structure. Once an array is
created, its size cannot be changed. Nevertheless, you can
still use array to implement dynamic data structures. The
trick is to create a new larger array to replace the current
array if the current array cannot hold new elements in the
list.
Initially, an array, say data of Object[] type, is created with
a default size. When inserting a new element into the array,
first ensure there is enough room in the array. If not, create
a new array with the size as twice as the current one. Copy
the elements from the current array to the new array. The
new array now becomes the current array.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
11
Insertion
Before inserting a new element at a specified index,
shift all the elements after the index to the right and
increase the list size by 1.
Before inserting
e at insertion point i
0
e0 e1
e
After inserting
e at insertion point i,
list size is
incremented by 1
1
…
i
… ei-1 ei
i+1 …
k-1 k
…
ek-1 ek
ei+1
Insertion point
0
1
e0 e1
…
i
… ei-1 e
data.length -1
…shift…
i+1 i+2 …
ei
ei+1
…
k
k+1
ek-1 ek
e inserted here
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
data.length -1
12
Deletion
To remove an element at a specified index, shift all
the elements after the index to the left by one
position and decrease the list size by 1.
Before deleting the
element at index i
0
1
e0 e1
…
i
… ei-1 ei
Delete this element
After deleting the
element, list size is
decremented by 1
0
1
e0 e1
…
i
… ei-1 ei+1
i+1 …
k-1 k
…
ek-1 ek
ei+1
…shift…
…
…
data.length -1
k-2 k-1
ek-1 ek
data.length -1
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
13
Implementing MyArrayList
MyAbstractList
MyArrayList
-data: Object[]
+MyArrayList()
Creates a default array list.
+MyArrayList(objects: Object[]) Creates an array list from an array of objects.
MyArrayList
TestList
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
14
Linked Lists
Since MyArrayList is implemented using an array,
the methods get(int index) and set(int index, Object
o) for accessing and modifying an element through
an index and the add(Object o) for adding an
element at the end of the list are efficient. However,
the methods add(int index, Object o) and remove(int
index) are inefficient because it requires shifting
potentially a large number of elements. You can use
a linked structure to implement a list to improve
efficiency for adding and remove an element
anywhere in a list.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
15
Nodes in Linked Lists
A linked list consists of nodes. Each node contains an
element, and each node is linked to its next neighbor. Thus
a node can be defined as a class, as follows:
head
Node 1
Node 2
element1
element2
next
next
Node n
…
element2
tail
null
class Node {
Object element;
Node next;
public Node(Object o) {
element = o;
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
16
Adding Three Nodes
The variable head refers to the first node in the list, and the
variable last refers to the last node in the list. If the list is
empty, both are null. For example, you can create three
nodes to store three strings in a list, as follows:
Step 1: Declare head and tail:
Node head = null;
Node tail = null;
The list is empty now
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
17
Adding Three Nodes, cont.
Step 2: Create the first node and insert it to the list:
head = new Node("Chicago");
last = head;
After the first node is inserted
inserted
"Chicago"
head
tail
next: null
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
18
Adding Three Nodes, cont.
Step 3: Create the second node and insert it to the
list:
tail
tail.next = new Node("Denver");
head
"Chicago"
"Denver"
next
next: null
tail
tail = tail.next;
head
"Chicago"
"Denver"
next
next: null
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
19
Adding Three Nodes, cont.
Step 4: Create the third node and insert it to the list:
tail
tail.next = new Node("Dallas");
head
"Chicago"
"Denver"
"Dallas"
next
next
next: null
tail
tail = tail.next;
head
"Chicago"
"Denver"
"Dallas"
next
next
next: null
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
20
Traversing All Elements in the List
Each node contains the element and a data field
named next that points to the next element. If the
node is the last in the list, its pointer data field next
contains the value null. You can use this property to
detect the last node. For example, you may write the
following loop to traverse all the nodes in the list.
Node current = head;
while (current != null) {
System.out.println(current.element);
current = current.next;
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
21
MyLinkedList
MyAbstractList
Node
m
1
element: Object
next: Node
MyLinkedList
-first: Node
-last: Node
1
+LinkedList()
Link
Creates a default linked list.
+LinkedList(objects: Object[]) Creates a linked list from an array of objects.
+addFirst(o: Object): void
Adds the object to the head of the list.
+addLast(o: Object): void
Adds the object to the tail of the list.
+getFirst(): Object
Returns the first object in the list.
+getLast(): Object
Returns the last object in the list.
+removeFirst(): Object
Removes the first object from the list.
+removeLast(): Object
Removes the last object from the list.
MyLinkedList
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
22
Implementing addFirst(Object o)
public void addFirst(Object o) {
Node newNode = new Node(o);
newNode.next = head;
head = newNode;
size++;
head
if (tail == null)
e
tail = head;
next
}
A new node
0
tail
…
to be inserted
element
here
next
ei
ei+1
next
next
…
ek
null
(a) Before a new node is inserted.
head
tail
element
e0
next
next
New node inserted here
…
ei
ei+1
next
next
…
ek
null
(b) After a new node is inserted.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
23
Implementing addLast(Object o)
public void addLast(Object o) {
if (tail == null) {
head = tail = new Node(element);
}
else {
tail.next = new Node(element);
tail = tail.next;
}
head
size++;
e
}
next
0
tail
…
ei
ei+1
next
next
…
ek
null
A new node
to be inserted
here
(a) Before a new node is inserted.
o
null
head
e0
next
tail
…
ei
ei+1
next
next
…
ek
o
next
null
(b) After a new node is inserted.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
New node inserted here
24
Implementing add(int index, Object o)
public void add(int index, Object o) {
if (index == 0) addFirst(o);
else if (index >= size) addLast(o);
else {
head
Node current = head;
e0
for (int i = 1; i < index; i++)
next
current = current.next;
Node temp = current.next;
current.next = new Node(o);
(current.next).next = temp;
size++;
}
head
}
ei
next
current
…
temp
ei
ei+1
next
next
tail
…
ek
null
A new node
to be inserted
o
here
next
(a) Before a new node is inserted.
current
…
temp
ei
o
ei+1
next
next
next
tail
…
ek
null
New node inserted here
(b) After a new node is inserted.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
25
Implementing removeFirst()
public Object removeFirst() {
if (size == 0) return null;
else {
Node temp = head;
head = head.next;
size--;
if (head == null) tail = null;
return temp.element;
}
}
tail
head
e0
e1
next
next
…
Delete this node
ei
ei+1
next
next
…
null
(a) Before the node is deleted.
head
e1
next
ek
tail
…
ei
ei+1
next
next
…
ek
null
(b) After the first node is deleted
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
26
public Object removeLast() {
if (size == 0) return null;
else if (size == 1)
{
Node temp = head;
head = tail = null;
size = 0;
return temp.element;
}
else
{
Node current = head;
for (int i = 0; i < size - 2; i++)
current = current.next;
Node temp = tail;
tail = current;
tail.next = null;
size--;
return temp.element;
}
}
Implementing
removeLast()
tail
current
head
…
e0
e1
next
next
ek-2
ek-1
ek
next
next
null
(a) Before the node is deleted.
Delete this node
tail
head
…
e0
e1
next
next
ek-2
ek-1
next
null
(b) After the last node is deleted
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
27
Implementing remove(int index)
public Object remove(int index) {
if (index < 0 || index >= size) return null;
else if (index == 0) return removeFirst();
else if (index == size - 1) return removeLast();
else {
Node previous = head;
for (int i = 1; i < index; i++) {
head
previous = previous.next;
…
element
}
next
Node current = previous.next;
previous.next = current.next;
size--;
return current.element;
head
}
}
…
element
next
previous
current
current.next
element
element
element
next
next
next
tail
…
element
null
Node to be deleted
(a) Before the node is deleted.
previous
current.next
element
element
next
next
tail
…
element
null
(b) After the node is deleted.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
28
Circular Linked Lists
A circular, singly linked list is like a singly
linked list, except that the pointer of the last node
points back to the first node.
head
Node 1
Node 2
element1
element2
next
next
Node n
…
element2
tail
next
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
29
Doubly Linked Lists
A doubly linked list contains the nodes with two
pointers. One points to the next node and the other
points to the previous node. These two pointers are
conveniently called a forward pointer and a backward
pointer. So, a doubly linked list can be traversed
forward and backward.
head
Node 1
Node 2
element1
element2
next
next
null
null
previous
previous
Node n
…
element2
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
tail
30
Circular Doubly Linked Lists
A circular, doubly linked list is doubly linked
list, except that the forward pointer of the last
node points to the first node and the backward
pointer of the first pointer points to the last node.
head
Node 1
Node 2
element1
element2
next
next
next
previous
previous
previous
Node n
…
element2
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
tail
31
Stacks
A stack can be viewed as a special type of list,
where the elements are accessed, inserted, and
deleted only from the end, called the top, of the
stack.
Data1
Data2
Data3
Data2
Data1
Data1
Data3
Data2
Data2
Data1
Data3
Data2
Data1
Data1
Data1
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
32
Queues
A queue represents a waiting list. A queue can be
viewed as a special type of list, where the
elements are inserted into the end (tail) of the
queue, and are accessed and deleted from the
beginning (head) of the queue.
Data1
Data2
Data3
Data2
Data1
Data1
Data3
Data2
Data1
Data3
Data3
Data2
Data1
Data2
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Data3
33
Implementing Stacks and Queues
Using
an array list to implement Stack
Use a linked list to implement Queue
Since the insertion and deletion operations on a
stack are made only at the end of the stack, using an
array list to implement a stack is more efficient than
a linked list. Since deletions are made at the
beginning of the list, it is more efficient to
implement a queue using a linked list than an array
list. This section implements a stack class using an
array list and a queue using a linked list.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
34
Design of the Stack and Queue Classes
There are two ways to design the stack and queue classes:
– Using inheritance: You can declare the stack class by
extending the array list class, and the queue class by
extending the linked list class.
MyArrayList
MyStack
MyLinkedList
MyQueue
– Using composition: You can declare an array list as a data field
in the stack class, and a linked list as a data field in the queue
class.
MyStack
MyArrayList
MyQueue
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
MyLinkedList
35
Composition is Better
Both designs are fine, but using composition is better
because it enables you to declare a complete new stack
class and queue class without inheriting the unnecessary
and inappropriate methods from the array list and linked
list.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
36
MyStack and MyQueue
MyStack
MyStack
-list: MyArrayList
+isEmpty(): boolean
Returns true if this stack is empty.
+getSize(): int
Returns the number of elements in this stack.
+peek(): Object
Returns the top element in this stack.
+pop(): Object
Returns and removes the top element in this stack.
+push(o: Object): Object
Adds a new element to the top of this stack.
+search(o: Object): int
Returns the position of the specified element in this stack.
MyQueue
MyQueue
-list: MyLinkedList
+enqueue(element: Object): void Adds an element to this queue.
+dequeue(): Object
Removes an element from this queue.
+getSize(): int
Returns the number of elements from this queue.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
37
Example: Using Stacks and Queues
Write a program that creates a stack using MyStack and a
queue using MyQueue. It then uses the push (enqueu)
method to add strings to the stack (queue) and the pop
(dequeue) method to remove strings from the stack
(queue).
TestStackQueue
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
38
Binary Trees
A list, stack, or queue is a linear structure that consists of a sequence
of elements. A binary tree is a hierarchical structure. It is either empty
or consists of an element, called the root, and two distinct binary
trees, called the left subtree and right subtree. Examples of binary
trees are shown in Figure 20.18.
60
G
55
45
F
100
57
67
(A)
107
R
M
A
T
(B)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
39
Binary Tree Terms
The root of left (right) subtree of a node is called a left
(right) child of the node. A node without children is called
a leaf. A special type of binary tree called a binary search
tree is often useful. A binary search tree (with no duplicate
elements) has the property that for every node in the tree
the value of any node in its left subtree is less than the
value of the node and the value of any node in its right
subtree is greater than the value of the node. The binary
trees in Figure 20.18 are all binary search trees. This
section is concerned with binary search trees.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
40
Representing Binary Trees
A binary tree can be represented using a set of linked
nodes. Each node contains a value and two links named
left and right that reference the left child and right child,
respectively, as shown in Figure 20.19.
class TreeNode {
Object element;
TreeNode left;
TreeNode right;
60
root
55
45
100
57
67
public TreeNode(Object o) {
element = o;
}
107
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
41
Inserting an Element to a Binary Tree
If a binary tree is empty, create a root node with the new
element. Otherwise, locate the parent node for the new
element node. If the new element is less than the parent
element, the node for the new element becomes the left
child of the parent. If the new element is greater than the
parent element, the node for the new element becomes the
right child of the parent. Here is the algorithm:
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
42
Inserting an Element to a Binary Tree
if (root == null)
root = new TreeNode(element);
Insert 101
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
into the following tree.
60
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
43
Trace Inserting 101 into the following tree
if (root == null)
root = new TreeNode(element);
Insert 101
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
into the following tree.
60
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
44
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
current
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
into the following tree.
60
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
45
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
current
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
into the following tree.
60
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
46
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
101 < 60?
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
current
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
the following tree.
60
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
47
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
101 > 60?
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
current
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
the following tree.
60
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
48
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
101 > 60 true
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
parent
else
current
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
following tree.
60
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
49
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
101 > 60 true
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
parent
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
following tree.
60
current
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
50
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
101 > 60 true
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
parent
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
following tree.
60
current
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
51
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
101 >
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
parent
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
into the following tree.
100 false
60
current
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
52
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the following
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
101 > 100 true
else if (element value > the value in current.element) {
parent = current;
current = current.right;
60
root
}
parent
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
tree.
current
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
53
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the following
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
101 > 100 true
else if (element value > the value in current.element) {
parent = current;
current = current.right;
60
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
tree.
parent
current
55
45
100
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
54
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the following
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
101 > 100 true
else if (element value > the value in current.element) {
parent = current;
current = current.right;
60
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
tree.
parent
55
100
current
45
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
55
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the following
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
101 > 100 true
else if (element value > the value in current.element) {
parent = current;
current = current.right;
60
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
tree.
parent
55
100
current
45
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
56
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the following
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
101 < 107 true
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
60
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
tree.
parent
55
100
current
45
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
57
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the following
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
101 < 107 true
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
60
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
tree.
parent
55
100
current
45
57
67
107
return true; // Element inserted
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
58
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101 into the following
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
101 < 107 true
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
60
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
tree.
parent
55
45
100
57
67
107
return true; // Element inserted
}
Since current.left is
null,current becomes null
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
59
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101
else {
// Locate the parent node
current = root;
current is null now
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
into the following tree.
60
parent
55
45
100
57
67
107
return true; // Element inserted
}
Since current.left is
null,current becomes null
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
60
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
101 < 107 true
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
into the following tree.
60
parent
55
45
100
57
67
107
return true; // Element inserted
}
Since current.left is
null,current becomes null
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
61
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
101 < 107 true
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
into the following tree.
60
parent
55
45
100
57
67
107
return true; // Element inserted
}
101
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
62
Trace Inserting 101 into the following tree, cont.
if (root == null)
root = new TreeNode(element);
Insert 101
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
root
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
101 < 107 true
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
into the following tree.
60
parent
55
45
100
57
67
107
return true; // Element inserted
}
101
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
63
Inserting 59 into the Tree
if (root == null)
root = new TreeNode(element);
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(elemenet);
else
parent.right = new TreeNode(elemenet);
60
root
55
45
100
57
67
107
return true; // Element inserted
}
59
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
101
64
Tree Traversal
Tree traversal is the process of visiting each node in the
tree exactly once. There are several ways to traverse a tree.
This section presents inorder, preorder, postorder, depthfirst, and breadth-first traversals.
The inorder traversal is to visit the left subtree of the
current node first, then the current node itself, and finally
the right subtree of the current node.
The postorder traversal is to visit the left subtree of the
current node first, then the right subtree of the current
node, and finally the current node itself.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
65
Tree Traversal, cont.
The breadth-first traversal is to visit the nodes level by
level. First visit the root, then all children of the root from
left to right, then grandchildren of the root from left to
right, and so on.
For example, in the tree in Figure 20.20, the inorder is 45
55 57 59 60 67 100 101 107. The postorder is 45 59 57 55
67 101 107 100 60. The preorder is 60 55 45 57 59 100 67
107 101. The breadth-first traversal is 60 55 100 45 57 67
107 59 101.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
66
The BinaryTree Class
Let’s define the binary tree class, named BinaryTree with
the insert, inorder traversal, postorder traversal, and
preorder traversal, as shown in Figure 20.21. Its
implementation is given as follows:
BinaryTree
TreeNode
m
1
BinaryTree
element: Object
-root: TreeNode
left: TreeNode
+BinaryTree()
right: TreeNode
+BinaryTree(objects: Object[]) Creates a binary tree from an array of objects.
+insert(o: Object): boolean
Adds an element to the binary tree.
1
Link
Creates a default binary tree.
+inorder(): void
Prints the nodes in inorder traversal.
+preorder(): void
Prints the nodes in preorder traversal.
+postorder(): void
Prints the nodes in postorder traversal.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
67
Example: Using Binary Trees
Write a program that creates a binary tree using
BinaryTree. Add strings into the binary tree and traverse
the tree in inorder, postorder, and preorder.
TestBinaryTree
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
68
Tree After Insertions
root
Inorder: Adam, Daniel
George, Jones, Michael,
Peter, Tom
George
Adam
Michael
Daniel
Jones
Tom
Peter
Postorder: Daniel Adam,
Jones, Peter, Tom,
Michael, George
Preorder: George, Adam,
Daniel, Michael, Jones,
Tom, Peter
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
69
Heap
Heap is a useful data structure for designing efficient
sorting algorithms and priority queues. A heap is a binary
tree with the following properties:
It
is a complete binary tree.
Each node is greater than or equal to any of its children.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
70
Complete Binary Tree
A binary tree is complete if every level of the tree is full
except that the last level may not be full and all the leaves
on the last level are placed left-most. For example, in
Figure 20.23, the binary trees in (a) and (b) are complete,
but the binary trees in (c) and (d) are not complete. Further,
the binary tree in (a) is a heap, but the binary tree in (b) is
not a heap, because the root (39) is less than its right child
(42).
42
32
22
39
39
29
14
32
33
22
42
29
14
42
42
32
22
32
39
14
33
22
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
29
71
Representing a Heap
For a node at position i, its left child is at position 2i+1 and
its right child is at position 2i+2, and its parent is (i-1)/2.
For example, the node for element 39 is at position 4, so its
left child (element 14) is at 9 (2*4+1), its right child
(element 33) is at 10 (2*4+2), and its parent (element 42) is
at 1 ((4-1)/2).
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11][12][13]
62
[10][11]
62 42 59 32 39 44 13 22 29 14 33 30 17 9
42
32
22
59
39
29
14
44
33
30 17
parent
13
left
right
9
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
72
Adding Elements to the Heap
Adding 3, 5, 1, 19, 11, and 22 to a heap, initially empty
3
5
5
3
3
(a) After adding 3
(b) After adding 5
19
5
1
(c) After adding 1
19
1
11
22
1
3
3
(d) After adding 19
(e) After adding 11
5
11
3
19
5
1
(f) After adding 22
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
73
Rebuild the heap after adding a new node
Adding 88 to the heap
22
22
11
3
19
5
1
88
(a) Add 88 to a heap
88
11
3
88
5
1
19
(b) After swapping 88 with 19
11
3
22
5
1
19
(b) After swapping 88 with 22
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
74
Removing the Root and Rebuild the Tree
Removing root 62 from the heap
62
42
32
22
59
39
29
14
44
33
30
13
17
9
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
75
Removing the Root and Rebuild the Tree
Move 9 to root
9
42
32
22
59
39
29
14
44
33
30
13
17
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
76
Removing the Root and Rebuild the Tree
Swap 9 with 59
59
42
32
22
9
39
29
14
44
33
30
13
17
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
77
Removing the Root and Rebuild the Tree
Swap 9 with 44
59
42
32
22
44
39
29
14
9
33
30
13
17
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
78
Removing the Root and Rebuild the Tree
Swap 9 with 30
59
42
32
22
44
39
29
14
30
33
9
13
17
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
79
The Heap Class
Heap
-list: java.util.ArrayList
+Heap()
Creates a default heap.
+Heap(objects: Object[])
Creates a heap with the specified objects.
+add(newObject: Object): void
Adds a new object to the heap.
+remove(): Object
Removes the root from the heap and returns it.
+getSize(): int
Returns the size of the heap.
Heap
TestHeap
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
80
Priority Queue
A regular queue is a first-in and first-out data structure. Elements are
appended to the end of the queue and are removed from the
beginning of the queue. In a priority queue, elements are assigned
with priorities. When accessing elements, the element with the
highest priority is removed first. A priority queue has a largest-in,
first-out behavior. For example, the emergency room in a hospital
assigns patients with priority numbers; the patient with the highest
priority is treated first.
MyPriorityQueue
-heap: Heap
+enqueue(element: Object): void
Adds an element to this queue.
+dequeue(): Object
Removes an element from this queue.
+getSize(): int
Returns the number of elements from this queue.
MyPriorityQueue TestPriorityQueue
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Run
81