10/2/2016
1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 1
CSC 249
Data Structures
Using Java
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
Lesson 6:
Binary Trees, Heaps,
Priority Queues, and
Binary Search Trees
10/2/2016
2
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
Chapter 23
Binary Trees and Heaps
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 4
Binary Trees
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.
60
55 100
57 67 107 45
G
F R
M T A
(A) (B)
10/2/2016
3
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 5
Binary Tree Terms
The root of the left subtree of a node is called the
left child of the node.
The root of the right subtree of a node is called the
right child of the node.
A node without children is called a leaf.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 6
Complete Binary Tree Example
For example: In the following figure:
The binary trees in (a) and (b) are complete
And the binary trees in (c) and (d) are not complete.
22 29 14 33
32 39
42
22 29 14
32 42
39
22 14 33
32 39
42
22 29
32
42
(a) (c)(b) (d)
10/2/2016
4
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 8
Heap Binary Tree Example
For example: In the following figure:
The binary tree in (a) is a heap.
The binary tree in (b) is not a heap, because the root (39) is less than its right child (42).
22 29 14 33
32 39
42
22 29 14
32 42
39
22 14 33
32 39
42
22 29
32
42
(a) (c)(b) (d)
10/2/2016
5
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
MaxHeap or MinHeap
MaxHeap: For each node in the heap, the value stored in that node is greater than or equal to the value in each of its children.
MinHeap: For each node in the heap, the value stored in that node is less than or equal to the value in each of its children.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Are these Max Heaps?
C
A T
treePtr
50
20
18
30
10
treePtr
10/2/2016
6
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Are these Max Heaps?
C
A T
treePtr
50
20
18
30
10
treePtr
NO
YES
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Is This a Max Heap?
70
60
40 30
12
8 10
treePtr
10/2/2016
7
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Is This a Max Heap?
70
60
40 30
12
8 10
treePtr
YES
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Max Heap
70
60
40 30
12
8 10
treePtr
Where is the Largest Element Always Found?
10/2/2016
8
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Max Heap
70
60
40 30
12
8 10
treePtr
Where is the Largest Element Always Found?
At the root
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Max Heap
70
60
40 30
12
8 10
treePtr
We can number the nodes from left to right by level:
0
2
5
1
43 6
10/2/2016
9
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Max Heap
70
0
60
1
40
3
30
4
12
2
8
5
root[ 0 ]
[ 1 ]
[ 2 ]
[ 3 ]
[ 4 ]
[ 5 ]
[ 6 ]
70
60
12
40
30
8
10
heap.elements
10
6
Use the numbers as array indexes
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Array Representation of Binary Tree
We can represent a heap in an array called:
heap_elements
Let index be the position in the array of a certain
node: heap_elements [index]
• Its left child is at position index*2+1:
heap_elements [index*2 + 1]
• Its right child is at position index*2+2:
heap_elements [index*2 + 2]
• Its parent is at position (index-1)/2:
heap_elements [(index – 1)/2].
10/2/2016
10
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Max Heap Order Property
The max heap order property says:
For every non-leaf node:
heap_elements [index]
LEFT CHILD:
heap_elements [index] >= heap_elements [index*2 + 1]
RIGHT CHILD:
heap_elements [index] >= heap_elements [index*2 + 2]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Min Heap Order Property
The min heap order property says:
For every non-leaf node:
heap_elements [index]
LEFT CHILD:
heap_elements [index] <= heap_elements [index*2 + 1]
RIGHT CHILD:
heap_elements [index] <= heap_elements [index*2 + 2]
10/2/2016
11
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Insertion and Deletion
Whenever, a node is inserted into or deleted from the heap, the Heap Order Property and the Heap Shape Property must be preserved.
Dequeue From Root: Remove root, and replace it
with the bottom rightmost element, then perform
reheapify to restore order property.
Enqueue At Bottom: Perform reheapify to restore
order property.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 22
See How a Max Heap Workshttp://www.cs.armstrong.edu/liang/animation/web/
Heap.html
10/2/2016
12
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 23
Max Heap Example
For example:
The node for element 39 is at position 4:
left child (element 14) is at 9 (2*4+1),
right child (element 33) is at 10 (2*4+2)
parent (element 42) is at 1 ((4-1)/2).
22 29 14 33 30 17 9
32 39 44 13
42 59
62 62 42 59 32 39 44 13 22 29 14 33 30 17 9
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11][12][13]
[10][11]
parent
left
right
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 24
Adding Elements to the Max Heap
Adding 3, 5, 1, 19, 11, and 22 to a heap, initially empty
3
(a) After adding 3 (b) After adding 5 (c) After adding 1
(d) After adding 19
3
19
5 1
(e) After adding 11
3 5
19
11 1
(f) After adding 22
3 5 1
22
11 19
5
3
5
3 1
10/2/2016
13
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 25
Rebuild the heap after adding a new node
Adding 88 to the heap
(a) Add 88 to a heap
3 5 1 88
22
11 19
(b) After swapping 88 with 19
3 5 1 19
22
11 88
(b) After swapping 88 with 22
3 5 1 19
88
11 22
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 26
Removing the Root and Rebuild the Tree
22 29 14 33 30 17 9
32 39 44 13
42 59
62
Removing root 62 from the heap
10/2/2016
14
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 27
Removing the Root and Rebuild the Tree
22 29 14 33 30 17
32 39 44 13
42 59
9
Move 9 to root
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 28
Removing the Root and Rebuild the Tree
22 29 14 33 30 17
32 39 44 13
42 9
59
Swap 9 with 59
10/2/2016
15
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
Removing the Root and Rebuild the Tree
22 29 14 33 30 17
32 39 9 13
42 44
59
Swap 9 with 44
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 30
Removing the Root and Rebuild the Tree
22 29 14 33 9 17
32 39 30 13
42 44
59
Swap 9 with 30
10/2/2016
16
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 31
The Heap Class
*****
This max Heap class can only contain objects that are
Comparable; that implement the Comparable interface
****
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 32
Heap Class
import java.util.ArrayList;
public class Heap<E extends Comparable<E>>
{
private ArrayList<E> list = new ArrayList<E>();
/** Create a default heap */
public Heap()
{
}
/** Create a heap from an array of objects */
public Heap(E[] objects)
{
for (int i = 0; i < objects.length; i++)
{
add(objects[i]);
}
}
10/2/2016
17
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 33
Heap Class/** Add a new object into the heap */
public void add(E newObject)
{
list.add(newObject); // Append to the heap
int currentInd = list.size()-1; // last node
while (currentInd > 0)
{
int parentInd = (currentInd - 1) / 2;
if (list.get(currentInd).compareTo
(list.get(parentInd)) > 0)
{
// Swap when current > parent
E temp = list.get(currentInd);
list.set(currentInd, list.get(parentInd));
list.set(parentInd, temp);
}
else break; // the tree is a heap now
currentInd = parentInd;
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 34
Heap Class/** Remove the root from the heap */
public E remove()
{
if (list.size() == 0) return null;
E removedObject = list.get(0);
list.set(0, list.get(list.size() - 1));
list.remove(list.size() - 1);
int currentInd = 0;
while (currentInd < list.size())
{
int ltChildInd = 2 * currentInd + 1;
int rtChildInd = 2 * currentInd + 2;
if (ltChildInd >= list.size()) break;
int maxInd = ltChildInd;
if (rtChildInd < list.size())
{
if (list.get(maxInd).compareTo
(list.get(rtChildInd)) < 0)
{
maxInd = rtChildInd;
}
}
10/2/2016
18
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 35
Heap Class// Swap if current < max
if (list.get(currentInd).compareTo
(list.get(maxInd)) < 0)
{
E temp = list.get(maxInd);
list.set(maxInd, list.get(currentInd));
list.set(currentInd, temp);
currentInd = maxInd;
}
else break; // The tree is a heap
}
return removedObject;
}
/** Get the number of nodes in the tree */
public int getSize()
{
return list.size();
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 36
Chapter 25
Binary Search Trees
10/2/2016
19
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
A binary tree is a structure with:
A unique starting node at the top called the root,
In which each node is capable of having at most two child nodes, called the left child and the right child, if they exist,
And in which a unique path exists from the root to every other node.
A tree node with no children is called a leaf.
Binary Tree
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 38
Binary Tree
A list, stack, or queue is a linear structure that
consists of a sequence of elements.
A binary tree is a recursive, 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.
Note: the recursion.
10/2/2016
20
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Owner
Jake
Manager Chef
Brad Carol
Waitress Waiter Cook Helper
Joyce Chris Max Len
Jake’s Pizza Shop
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Owner
Jake
Manager Chef
Brad Carol
Waitress Waiter Cook Helper
Joyce Chris Max Len
ROOT NODE
Jake: The Root
10/2/2016
21
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Owner
Jake
Manager Chef
Brad Carol
Waitress Waiter Cook Helper
Joyce Chris Max Len
LEAF NODES
Joyce, Chris, Max, Len – The Leaves
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Each of the root node’s children is itself the root of a smaller binary tree, or subtree
Level: distance of a node from the root; the root is at level 0
Height: the tree’s maximum level.
Descendants: all nodes that are part of a node’s left and right subtrees.
Ancestors: the parent node and its parent nodes and grandparent nodes. etc.
Binary Tree Definitions
10/2/2016
22
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Owner
Jake
Manager Chef
Brad Carol
Waitress Waiter Cook Helper
Joyce Chris Max Len
LEVEL 0
Level 0: Jake, The Owner
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Owner
Jake
Manager Chef
Brad Carol
Waitress Waiter Cook Helper
Joyce Chris Max Len
LEVEL 1
Level 1: The Manager and Chief Chef
10/2/2016
23
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Owner
Jake
Manager Chef
Brad Carol
Waitress Waiter Cook Helper
Joyce Chris Max Len
LEVEL 2
Level 2: The Worker Bees
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Owner
Jake
Manager Chef
Brad Carol
Waitress Waiter Cook Helper
Joyce Chris Max Len
LEFT SUBTREE OF ROOT NODE
Left Subtree: The Wait Staff
10/2/2016
24
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Owner
Jake
Manager Chef
Brad Carol
Waitress Waiter Cook Helper
Joyce Chris Max Len
RIGHT SUBTREE
OF ROOT NODE
Right Subtree: The Cook Staff
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
A Binary Tree
Q
V
T
K S
AE
L
10/2/2016
25
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
How Many Leaf Nodes?
Q
V
T
K S
AE
L
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
How Many Leaf Nodes?
Q
V
T
K S
AE
L
3 Leaf Nodes: E K S
10/2/2016
26
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
How Many Descendants of Q?
Q
V
T
K S
AE
L
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
How Many Descendants of Q?
Q
V
T
K S
AE
L
3 Descendants of Q: E T K
10/2/2016
27
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
How Many Ancestors of K?
Q
V
T
K S
AE
L
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
How Many Ancestors of K?
Q
V
T
K S
AE
L
3 Ancestors of K: T Q V
10/2/2016
28
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 55
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Node Terminology for a TreeNode
class TreeNode <E>
{
E element;
TreeNode <E> left;
TreeNode <E> right;
public TreeNode (E o)
{
element = o;
}
}
TreeNode
left(TreeNode) right(TreeNode)
element
10/2/2016
29
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
A special kind of binary tree in which:
Each node contains a distinct data value,
The key values in the tree can be compared using
“greater than” and “less than”, and
The key value of each node in the tree is both
less than every key value in its right
subtree
greater than every key value in its left
subtree.
Binary Search Tree: BST
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Insertion into the Tree
Tree shape depends on its key values and their order
of insertion.
Example:
Insert the elements ‘J’ ‘E’ ‘F’ ‘T’ ‘A’ in that
order.
The first value to be inserted is put into the root node:
‘J’
Binary Search Tree Shape
10/2/2016
30
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Inserting ‘J’ as the root in the BST
After root insertion:
Each value to be inserted begins by comparing itself to
the value in the root node.
Moving left it is less, or moving right if it is greater.
This continues at each level until it can be inserted as a
new leaf.
Binary Search Tree Shape
‘J’
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Inserting ‘E’ into the BST
Compare ‘E’ to ‘J’, and move left, as it is less.
Place ‘E’ as a leaf.
Binary Search Tree Shape
‘J’
‘E’
10/2/2016
31
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Inserting ‘F’ into the BST
Compare ‘F’ to ‘J’, and move left, as it is less.
Then, compare ‘F’ to ‘E’, and move right, as it is
greater.
Place ‘F’ as a leaf.
Binary Search Tree Shape
‘J’
‘E’
‘F’
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Inserting ‘T’ into the BST
Compare ‘T’ to ‘J’, and move right, as it is
greater.
Place ‘T’ as a leaf.
Binary Search Tree Shape
‘J’
‘E’
‘F’
‘T’
10/2/2016
32
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Inserting ‘A’ into the BST
Compare ‘A’ to ‘J’, and move left, as it is less.
Then, compare ‘A’ to ‘E’, and move left, as it is
less.
Place ‘A’ as a leaf.
Binary Search Tree Shape
‘J’
‘E’
‘F’
‘T’
‘A’
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
What BST is obtained by inserting these same
elements in this order:
‘A’ ‘E’ ‘F’ ‘J’ ‘T’
Binary Search Tree Shape
‘A’
10/2/2016
33
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
What BST is obtained by inserting these same
elements in this order:
‘A’ ‘E’ ‘F’ ‘J’ ‘T’
Binary Search Tree Shape
‘A’
‘E’
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
What BST is obtained by inserting these same
elements in this order:
‘A’ ‘E’ ‘F’ ‘J’ ‘T’
Binary Search Tree Shape
‘A’
‘E’
‘F’
10/2/2016
34
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
What BST is obtained by inserting these same
elements in this order:
‘A’ ‘E’ ‘F’ ‘J’ ‘T’
Binary Search Tree Shape
‘A’
‘E’
‘F’
‘J’
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
What BST is obtained by inserting these same
elements in this order:
‘A’ ‘E’ ‘F’ ‘J’ ‘T’
Binary Search Tree Shape
‘A’
‘E’
‘F’
‘J’
‘T’
10/2/2016
35
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Binary Search Tree Insertion
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 70
See How a Binary Search Tree Works
www.cs.armstrong.edu/liang/animation/web/BST.
html
10/2/2016
36
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 71
Tree Interface and AbstractTree Class
The AbstractTree class partially implements Tree.
The Tree interface defines common operations for trees.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 72
Tree Interfacepublic interface Tree<E> extends Iterable <E>
{
/** Return true if the element is in the tree */
public boolean search (E e);
/** Insert element o into the binary tree
* Return true if element is inserted successfully */
public boolean insert (E e);
/** Delete the specified element from the tree
* Return true if element is deleted successfully */
public boolean delete (E e);
/** Inorder traversal from the root */
public void inorder();
/** Postorder traversal from the root */
public void postorder();
/** Preorder traversal from the root */
public void preorder();
/** Get the number of nodes in the tree */
public int getSize();
/** Return true if the tree is empty */
public boolean isEmpty();
}
10/2/2016
37
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 73
AbtractTree Classpublic abstract class AbstractTree<E> implements Tree<E>
{
/** Inorder traversal from the root*/
@Override
public void inorder() { }
/** Postorder traversal from the root */
@Override
public void postorder() { }
/** Preorder traversal from the root */
@Override
public void preorder() { }
/** Return true if the tree is empty */
@Override
public boolean isEmpty()
{
return getSize() == 0;
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 74
Searching For an Element Algorithm
The search for an element starts at the root.
If a binary tree is empty, return false.
Otherwise, compare the element to the root and
if less than the root, look for the element in the left subtree
if greater than the root, look for the element in the right subtree.
if equal to the root, return true.
Repeat the search with the root of the subtree chosen.
10/2/2016
38
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 75
search Methodpublic boolean search (E e)
{
TreeNode<E> current = root; // Start from the root
while (current != null)
{
int comp = e.compareTo (current.element);
if (comp < 0)
{
current = current.left; // Go left
}
else if (comp > 0)
{
current = current.right; // Go right
}
else // Element e matches current.element
{
return true; // Element e is found
}
}
return false; // Element e is not in the tree
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 76
Inserting an Element Algorithm
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.
10/2/2016
39
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 77
Inserting an Element into a BST
Insert 101 into the following tree.
60
55 100
57 45 67 107
root
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 78
Inserting an Element into a BST
Insert 101 into the following tree.
60
55 100
57 45 67 107
root
current
10/2/2016
40
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 79
Inserting an Element into a BST
101 < 60? False
101 > 60? True
60
55 100
57 45 67 107
root
current parent
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 80
Inserting an Element into a BST
101 < 60? False
101 > 60? True
60
55 100
57 45 67 107
root
current
parent
10/2/2016
41
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 81
Inserting an Element into a BST
101 < 100? False
101 > 100? True
60
55 100
57 45 67 107
root
current
parent
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 82
Inserting an Element into a BST
101 < 100? False
101 > 100? True
60
55 100
57 45 67 107
root
current
parent
10/2/2016
42
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 83
Inserting an Element into a BST
101 < 107? True
60
55 100
57 45 67 107
root
current
parent
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 84
Inserting an Element into a BST
101 < 107? True
current == null
60
55 100
57 45 67 107
root
parent
10/2/2016
43
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 85
Inserting an Element into a BST
101 < 107? True
parent.left = Node:101
60
55 100
57 45 67 107
root
parent
101
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 86
insert Methodpublic boolean insert (E e)
{
if (root == null)
{
root = new TreeNode<E> (e);
}
else
{
current = root; // Locate the parent node
while (current != null)
{
int comp = e.compareTo (current.element);
if (comp < 0)
{
parent = current;
current = current.left;
}
else if (comp > 0)
{
parent = current;
current = current.right;
}
10/2/2016
44
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 87
insert Method
else
{
return false; // Duplicate node not inserted
}
}
// Create the new node and
// attach it to the parent node
if (e.compareTo (parent.element) < 0)
{
parent.left = new TreeNode<E> (e);
}
else
{
parent.right = new TreeNode<E> (e);
}
}
size++;
return true; // Element inserted
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 88
Deleting an Element Algorithm
To delete an element from a binary tree, you need to first
locate the node that contains the element and also its
parent node.
Let current point to that node that contains the element
to be deleted and parent point to the parent of the current
node.
The current node may be a left child or a right child of
the parent node.
There are two cases to consider.
10/2/2016
45
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 89
Deleting an Element Algorithm
Case 1: The current node does not have a left child, as
shown below.
Simply connect the parent with the right child of the
current node.
parent
current
No left child
Subtree
parent
Subtree
current may be a left or
right child of parent Subtree may be a left or
right subtree of parent
current points the node
to be deleted
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 90
Deleting an Element Algorithm
Case 1 example: Delete node containing 10:
20
10 40
30 80
root
50
16
27
20
40
30 80
root
50
16
27
10/2/2016
46
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 91
Deleting an Element Algorithm
Case 2: The current node has a left child.
Let rightMost point to the node that contains the largest
element in the left subtree of the current node
Let parentOfRightMost point to the parent node of the
rightMost node
Note that the rightMost node cannot have a right child, but
may have a left child.
Replace the element value in the current node with the one in
the rightMost node
Connect the parentOfRightMost node with the left child of
the rightMost node, and delete the rightMost node
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 92
Deleting Elements in a BST Case 2 diagram
parent
current
.
.
.
rightMost
parentOfRightMost
parent
.
.
.
parentOfRightMost
Content copied to
current and the node
deleted
Right subtree Right subtree
current
current may be a left or
right child of parent
current points the node
to be deleted
The content of the current node is
replaced by content by the content of
the right-most node. The right-most
node is deleted.
leftChildOfRightMost leftChildOfRightMost
10/2/2016
47
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 93
Deleting Elements in a BST
Case 2 example: delete node containing 20
rightMost
20
10 40
30 80
root
50
16
27
16
10 40
30 80
root
50 27 14 14
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 94
Delete George
Delete this
node George
Adam Michael
Daniel Jones Tom
Peter
Daniel
Adam Michael
Jones Tom
Peter
10/2/2016
48
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 95
Delete Adam
Daniel
Adam Michael
Jones Tom
Peter
Delete this
node
Daniel
Michael
Jones Tom
Peter
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 96
delete Methodpublic boolean delete (E e)
{
TreeNode<E> parent = null;
TreeNode<E> current = root;
// Locate the node to be deleted and its parent
while (current != null)
{
int comp = e.compareTo (current.element);
if (comp < 0)
{
parent = current;
current = current.left;
}
else if (comp > 0)
{
parent = current;
current = current.right;
}
else break;
}
10/2/2016
49
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 97
delete Method
if (current == null)
{
return false; // Node not found
}
// Case 1: current node has no left child
if (current.left == null)
{
if (parent == null)
{
root = current.right;
}
else
{
if (e.compareTo (parent.element) < 0)
parent.left = current.right;
else
parent.right = current.right;
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 98
delete Method
// Case 2: current node has a left child
else
{
TreeNode<E> parentOfRightMost = current;
TreeNode<E> rightMost = current.left;
// Keep going to the right
while (rightmost.right != null)
{
parentOfRightMost = rightmost;
rightmost = rightmost.right;
}
// Replace the element in current
// by the element in rightmost
current.element = rightmost.element;
10/2/2016
50
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 99
delete Method
// Delete rightmost node
if (parentOfRightmost.right == rightmost)
{
parentOfRightMost.right = rightmost.left;
}
else
{
parentOfRightMost.left = rightmost.left;
}
}
size--;
return true;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 100
Tree Traversal
Tree traversal is the process of visiting each node in the tree exactly once.
There are several ways to traverse a tree:
inorder traversal
preorder traversal
postorder traversal
depth-first traversal
breadth-first traversal
10/2/2016
51
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 101
Tree Traversal
The inorder traversal is to visit the left subtree of the current node first recursively, then the current node itself, and finally the right subtree of the current node recursively.
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 102
Tree Traversal
The preorder traversal is to visit the current node first, then the left subtree of the current node first recursively, then the right subtree of the current node recursively.
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
The depth-first traversal is the same as thepreorder traversal
10/2/2016
52
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 103
In-order Tree Traversal
In-order: A, B, C, D, E, F, G, H, I
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 104
inorder Methods
/** Inorder traversal from the root */
@Override
public void inorder()
{
inorder (root);
}
/** Inorder traversal from a subtree */
protected void inorder (TreeNode<E> subRoot)
{
if (subRoot == null)
return;
inorder (subRoot.left);
System.out.print (subRoot.element + " ");
inorder (subRoot.right);
}
10/2/2016
53
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 105
Pre-order (Depth-First Search)
Tree Traversal
Pre-order: F, B, A, D, C, E, G, I, H
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 106
preorder Methods
/** Preorder traversal from the root */
@Override
public void preorder()
{
preorder (root);
}
/** Preorder traversal from a subtree */
protected void preorder (TreeNode<E> subRoot)
{
if (subRoot == null)
return;
System.out.print (subRoot.element + " ");
preorder (subRoot.left);
preorder (subRoot.right);
}
10/2/2016
54
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 107
Post-order Tree Traversal
Post-order: A, C, E, D, B, H, I, G, F
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 108
postorder Methods
/** Postorder traversal from the root */
@Override
public void postorder()
{
postorder (root);
}
/** Postorder traversal from a subtree */
protected void postorder (TreeNode<E> subRoot)
{
if (subRoot == null)
return;
postorder (subRoot.left);
postorder (subRoot.right);
System.out.print (subRoot.element + " ");
}
10/2/2016
55
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 109
Breadth-First Search Tree Traversal
Level-order: F, B, G, A, D, I, C, E, H
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
A tree can have leaves and internal nodes.
Leaves have no children.
Internal nodes have either a left child or right child
(or both).
These left and right children are roots of the full tree’s
subtrees.
Each subtree is also a tree with the capability of having
leaves and internal nodes.
Thus the definition of a tree is recursive.
Recursive Binary Search Tree
10/2/2016
56
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Three of the methods of tree traversal have a recursive
solution, as shown above:
inorder traversal
preorder traversal
postorder traversal
The breadth-first search traversal uses a queue and is
not written recursively.
Recursive methods can be written for:
insert traversal
search traversal
delete traversal
Recursive Binary Search Tree
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Recursively Insert Item 12
12
10/2/2016
57
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Algorithm for Recursive insert Method
Just pseudo-code below:
boolean insert (TreeNode parent, TreeNode current,
E newElem)
{
found = false
if (current is null)
Create new node for the newElem and connect
to parent, if parent is not null
found = true
else
if (newElem < root.element)
Call insert to search in left subtree
else
Call insert to search in right subtree
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 114
insert Method for Recursion
/**
* Insert element ‘e’ into the binary tree
* Return true if the element is inserted successfully
*/
@Override
public boolean insert (E e)
{
// Call insert with parent, current, and element
// Note that to begin with the current node is the
// root node, which has no parent
boolean inserted = insert (null, root, e);
return inserted ;
}
10/2/2016
58
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 115
Recursive insert Method// Recursively inserts element into tree.
boolean insert(TreeNode<E> parent, TreeNode<E> current, E e)
{
boolean found = false;
if (root == null)
{
root = new TreeNode<>(e);
size++;
return true;
}
if (current == null)
{
if (e.compareTo (parent.element) < 0)
parent.left = new TreeNode<>(e);
else
parent.right = new TreeNode<> (e);
size++;
return true;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 116
Recursive insert Method
int comp = e.compareTo (current.element);
if (comp < 0) // Look in left subtree.
{
insert (current, current.left, e);
}
else if (comp > 0) // Look in right subtree.
{
insert (current, current.right, e);
}
else // Node found
{
return false; // Duplicate node not inserted
}
return true;
}
10/2/2016
59
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Algorithm for Recursive search Method
Just pseudo-code below:
boolean search (TreeNode root, E elem)
{
found = false
if (root is not null)
if (elem < root.element)
Call search to search in left subtree
else if (elem > root.element)
Call search to search in right subtree
else
found = true;
return found
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 118
search Method for Recursion
/**
* Return true if the element is in the tree
*/
@Override
public boolean search (E e)
{
// Call search with current and element
// The search is started at the root
boolean found = search (root, e);
return found;
}
10/2/2016
60
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 119
Recursive search Method// Recursively searches for element in tree.
boolean search (TreeNode<E> current, E e)
{
boolean found = false;
if (current != null)
{
int comp = e.compareTo (current.element);
if (comp < 0) // Look in left subtree.
{
found = search (current.left, e);
}
else if (comp > 0) // Look in right subtree.
{
found = search (current.right, e);
}
else // Node found
{
found = true;
}
}
return found;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Deleting a Leaf Node
10/2/2016
61
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Deleting a Node with One Child
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Deleting a Node with Two Children
10/2/2016
62
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Algorithm for Recursive remove Method
The remove method is called by delete
Algorithm:
if (delElem < root.element)
Call remove to search in left subtree
else if (delElem > root.element)
Call remove to search in right subtree
else
Call deleteNode;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 124
delete Method for Recursion
/**
* Delete an element from the binary tree.
* Return true if the element is deleted
* successfully
*/
@Override
public boolean delete (E e)
{
// Call remove with parent, current, and element
boolean removed = remove (null, root, e);
if (removed)
{
size--;
}
return removed;
}
10/2/2016
63
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 125
Recursive delete Method// Recursively deletes element from tree.
boolean remove (TreeNode<E> parent, TreeNode<E> tree, E e)
{
boolean found = false;
if (tree == null)
return false;
int comp = e.compareTo (tree.element);
if (comp < 0) // Look in left subtree.
{
found = remove (tree, tree.left, e);
}
else if (comp > 0) // Look in right subtree.
{
found = remove (tree, tree.right, e);
}
else // Node found
{
deleteNode (parent, tree);
found = true;
}
return found;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 126
deleteNode Method for Recursion// Deletes the node pointed to by tree.
// If tree is a leaf node or has only one non-NULL child
// pointer the node pointed to by tree is deleted;
// otherwise, the user's data is replaced by its logical
// predecessor (rightmost node) and that is deleted.
void deleteNode (TreeNode<E> parent, TreeNode<E> tree)
{
if (tree.left == null)
{
if (tree == root)
{
root = tree.right;
}
else if (tree.element.compareTo (parent.element) < 0)
{
parent.left = tree.right;
}
10/2/2016
64
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 127
deleteNode Method for Recursion
else
{
parent.right = tree.right;
}
}
else
{
// Get element from the right-most node in tree.
TreeNode<E> parentOfRightMost = tree;
TreeNode<E> rightMost = tree.left;
// Keep going to the right
while (rightMost.right != null)
{
parentOfRightMost = rightMost;
rightMost = rightMost.right;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 128
deleteNode Method for Recursion
// Replace the element in current with
// the element in rightmost
tree.element = rightMost.element;
// Delete rightmost node
if (parentOfRightMost.right == rightMost)
{
parentOfRightMost.right = rightMost.left;
}
else
{
parentOfRightMost.left = rightMost.left;
}
}
}
10/2/2016
65
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 129
The BST Class
The BST class is a concrete class that extends AbstractTree
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 130
BST Classimport java.util.*;
public class BST <E extends Comparable<E>> extends AbstractTree<E>
{
protected TreeNode<E> root;
protected int size = 0;
/** Create a default binary tree */
public BST()
{ }
/** Create a binary tree from an array of objects */
public BST (E[] objects)
{
for (int i = 0; i < objects.length; i++)
insert (objects[i]);
}
/** Get the number of nodes in the tree */
@Override
public int getSize()
{
return size;
}
10/2/2016
66
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 131
BST Class/** Returns the root of the tree */
public TreeNode<E> getRoot()
{
return root;
}
/** This inner class is static, because it does not access
* any instance members defined in the BST class */
public static class TreeNode <E extends Comparable<E>>
{
protected E element;
protected TreeNode<E> left;
protected TreeNode<E> right;
public TreeNode(E e)
{
element = e;
}
@Override
public int compareTo (TreeNode<E> node)
{
return element.compareTo (node.element);
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 132
BST Class/** Returns true if the element is in the tree */
@Override
public boolean search (E e)
{
// See earlier code
}
/** Insert element o into the binary tree
* Return true if the element is inserted successfully */
@Override
public boolean insert (E e)
{
// See earlier code
}
/** Delete an element from the binary tree.
* Return true if the element is deleted successfully
* Return false if the element is not in the tree */
@Override
public boolean delete (E e)
{
// See earlier code
}
10/2/2016
67
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 133
BST Class
/** Inorder traversal from the root */
@Override
public void inorder()
{
// See earlier code
}
/** Inorder traversal from a subtree */
protected void inorder (TreeNode<E> subRoot)
{
// See earlier code
}
/** Postorder traversal from the root */
@Override
public void postorder()
{
// See earlier code
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 134
BST Class
/** Postorder traversal from a subtree */
protected void postorder (TreeNode<E> subRoot)
{
// See earlier code
}
/** Preorder traversal from the root */
@Override
public void preorder()
{
// See earlier code
}
/** Preorder traversal from a subtree */
protected void preorder (TreeNode<E> subRoot)
{
// See earlier code
}
10/2/2016
68
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 135
BST Class/** Returns a path from the root
* leading to the specified element */
public MyArrayList <TreeNode<E>> path (E e)
{
MyArrayList <TreeNode<E>> list = new MyArrayList<>();
TreeNode<E> current = root; // Start from the root
while (current != null)
{
list.add (current); // Add the node to the list
int comp = e.compareTo (current.element);
if (comp < 0)
{
current = current.left;
}
else if (comp > 0)
{
current = current.right;
}
else break;
}
return list; // Return an array list of nodes
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 136
BST Class/** Remove all elements from the tree */
public void clear()
{
root = null;
size = 0;
}
/** Obtain an iterator. Use inorder. */
@Override
public Iterator<E> iterator()
{
return new InorderIterator();
}
// Inner class InorderIterator
private class InorderIterator implements Iterator<E>
{
// Store the elements in a list
private MyArrayList<E> list = new MyArrayList<>();
private int current = 0; // Pt to the cur element in list
public InorderIterator()
{
inorder(); // Traverse BST; store elements in list
}
10/2/2016
69
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 137
BST Class
/** Inorder traversal from the root*/
private void inorder()
{
inorder (root);
}
/** Inorder traversal from a subtree */
private void inorder (TreeNode<E> root)
{
if (root == null)
return;
inorder (root.left);
list.add (root.element);
inorder (root.right);
}
/** More elements for traversing? */
@Override
public boolean hasNext()
{
if (current < list.size())
return true;
return false;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 138
BST Class
/** Get the current element and move to the next */
@Override
public E next()
{
return list.get (current++);
}
/** Remove the current element */
@Override
public void remove()
{
// Delete the current element
delete (list.get (current));
// Clear the list
list.clear();
// Rebuild the list
inorder();
}
}
}
10/2/2016
70
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 139
TestBST Program
Write a program that creates a binary tree using BST.
Add elements into the binary tree and traverse the tree in inorder, postorder, and preorder.
Search for an element in the tree and create a list containing the path from the root to a given element and display the nodes in the path.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 140
TestBST Programpublic class TestBST
{
public static void main(String[] args)
{
// Create a BST for strings
BST<String> tree = new BST<>();
// Add the nodes
tree.insert("George");
tree.insert("Michael");
tree.insert("Tom");
tree.insert("Adam");
tree.insert("Jones");
tree.insert("Peter");
tree.insert("Daniel");
// Traverse tree
System.out.print("Inorder (sorted): ");
tree.inorder();
10/2/2016
71
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 141
TestBST ProgramSystem.out.print("\nPostorder: ");
tree.postorder();
System.out.print("\nPreorder: ");
tree.preorder();
System.out.print("\nThe number of nodes is " +
tree.getSize());
// Search for an element
System.out.print("\nIs Peter in the tree? " +
tree.search("Peter"));
// Get a path from the root to Peter
System.out.print("\nA path from the root to
Peter is: ");
MyArrayList<BST.TreeNode<String>> path =
tree.path("Peter");
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 142
TestBST Program
for (int i = 0; path != null &&
i < path.size(); i++)
{
System.out.print (path.get(i).element + " ");
}
// Create a BST for strings
Integer[] numbers = {2, 4, 3, 1, 8, 5, 6, 7};
BST<Integer> intTree = new BST<> (numbers);
// Traverse the Tree in order
System.out.print ("\nInorder (sorted): ");
intTree.inorder();
}
}
10/2/2016
72
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 143
Tree Traversals
George
Adam Michael
Daniel Jones Tom
root
Peter
Inorder: Adam,
Daniel George, Jones,
Michael, Peter, Tom
Postorder: Daniel
Adam, Jones, Peter,
Tom, Michael, George
Preorder: George,
Adam, Daniel,
Michael, Jones, Tom,
Peter
The tree after insertions
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 144
public class TestBSTDelete
{
public static void main(String[] args)
{
// Create a BST for strings
BST<String> tree = new BST<>();
// Add the nodes
tree.insert("George");
tree.insert("Michael");
tree.insert("Tom");
tree.insert("Adam");
tree.insert("Jones");
tree.insert("Peter");
tree.insert("Daniel");
// Print the tree
printTree(tree);
TestBSTDelete Program
10/2/2016
73
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 145
// Print the tree after each deletion
System.out.println("\nAfter delete George:");
tree.delete("George");
printTree(tree);
System.out.println("\nAfter delete Adam:");
tree.delete("Adam");
printTree(tree);
System.out.println("\nAfter delete Michael:");
tree.delete("Michael");
printTree(tree);
}
TestBSTDelete Program
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 146
public static void printTree(BST tree)
{
// Traverse tree inorder
System.out.print("Inorder (sorted): ");
tree.inorder();
// Traverse tree postorder
System.out.print("\nPostorder: ");
tree.postorder();
// Traverse tree preorder
System.out.print("\nPreorder: ");
tree.preorder();
// print number of nodes
System.out.print("\nThe number of nodes is "
+ tree.getSize());
System.out.println();
}
}
TestBSTDelete Program
10/2/2016
74
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 147
Delete Element From BST
Daniel
Michael
Jones Tom
Peter
Delete this
node
Daniel
Jones
Tom
Peter
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 148
TestBSTWithIterator Program
An iterator is an object that provides a uniform
way for traversing the elements in a container
such as a set, list, binary tree, etc.
10/2/2016
75
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 149
TestBSTWithIteratorpublic class TestBSTWithIterator
{
public static void main(String[] args)
{
BST<String> tree = new BST<>();
tree.insert ("George");
tree.insert ("Michael");
tree.insert ("Tom");
tree.insert ("Adam");
tree.insert ("Jones");
tree.insert ("Peter");
tree.insert ("Daniel");
for (String s: tree) // Uses iterator
{
System.out.print (s.toUpperCase() + " ");
}
}
}