0% found this document useful (0 votes)
53 views

Trees

The document describes data structures including trees, priority queues, binary search trees, balanced trees, and dictionaries. It provides details on tree terminology, different types of trees such as binary trees and their properties. It also covers tree traversals, priority queues, heap data structures, and algorithms for insertion and removal in binary heaps.

Uploaded by

Marfelino
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Trees

The document describes data structures including trees, priority queues, binary search trees, balanced trees, and dictionaries. It provides details on tree terminology, different types of trees such as binary trees and their properties. It also covers tree traversals, priority queues, heap data structures, and algorithms for insertion and removal in binary heaps.

Uploaded by

Marfelino
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 189

Data Structures.

2017/18
Grado en Informática, Ingeniería del Software y Computadores
ETSI Informática
Universidad de Málaga

@ José E. Gallardo
Dpto. Lenguajes y Ciencias de la Computación
Universidad de Málaga
 Trees
 Terminology, definition
 Binary trees.
▪ Proper, perfect and complete binary trees
▪ Traversals
 Priority Queues
 Signature, specification
 Algebraic implementation
 Binary Heaps
 Weight Biased Leftist Heaps
 Binary Search Trees
 Balanced Trees
 AVL trees
 Dictionaries
2
 Are the most important nonlinear structures

 Relationship of elements is hierarchical


 Richer than before and after

 Trees are a breakthrough in data organization


 Many algorithms are much faster using trees

3
 Trees store data hierarchically
 Each element has a parent (except for the root)
 Each element has zero or more children
▪ Elements with zero children are leafs
▪ Rest of them are internal nodes

 Trees are usually drawn upside down:


root

2 is parent Internal
of 5 and 6 node

6 is a child
5 is a
of 2
child of 2

leaf 4
 Parent of the parent is grandparent
 Children of the same parent are siblings
 An edge is a pair of nodes (u,v) such that u is the parent of v
 A path is a sequence of nodes such that any two consecutive
nodes form an edge 1 is grandparent of
5, 6, 7, 8 y 9

A path
An edge

6 is sibling of 5 5
 A tree is a set of nodes with a parent-child
relationship, such that:
 If set is empty, tree is an empty tree
 Otherwise:
▪ There is a node with no parent (root)
▪ Rest of nodes can be partitioned into different subsets so that
each subset is also a tree

6
Constructor for empty trees Value in node List of subtrees

A leaf

Adds all values in a


numeric tree

Pattern. a Pattern.
7
 Data in a tree is organized in Level 0
different levels:
 Root is at level 0
Level 1
 Children of root are at level 1
 Grandchildren of root are at level 2
 etc.
Level 2

 Height of a tree is number of levels in tree:

8
 Binary tree:
 Every node has at most two children

 Children are labeled left or right child

9
 Proper Binary Tree:
 Every node other than the
leaves has two children

 A Complete Binary Tree:


 Every level, except possibly
last one, is completely filled.
If last level is not filled, all
nodes are as far left as possible

 A Perfect Binary Tree:


 Proper Binary Tree with all
leaves at same level
10
 n: number of nodes
 h: height of tree

 For any non-empty Binary Tree:


 h ≤ n ≤ 2h-1
 1+⌊log2(n)⌋ ≤ h ≤ n
3 ≤ n ≤ 23 -1
n= 7
h= 3

1+⌊log2(7)⌋ ≤ h ≤ 7
11
Value at node Right subtree
Constructor for empty trees
Left subtree

Left subtree Right subtree

12
Level 0

Level 1

Level 2

13
14
 Tree-traversal: process of visiting each node in a tree,
exactly once, in a systematic way.

 Traversals are classified by the order in which the nodes


are visited.

 Most usual traversals of a binary tree (can also be


generalised to general trees):
 Pre-Order
 In-Order (aka Depth First)
 Post-Order
 Breadth First
15
16
 Priority Queue:
 Stores prioritized elements
 Elements can be inserted in arbitrary order
 Elements are removed according to their priorities:
▪ Element with highest priority (minimum value) is removed firstly
▪ Elements with same priority are removed using FIFO policy

17
18
19
Notice use of (less than) insteod
of (less than or equal) in

We keep elements in queue


sorted in ascending order

Recursively place after


in queue.
O(n) 

20
First element is always
minimum one

Exercise: implent Priority


Queues in Java using a
sorted linked list

21
 The running costs for this implementation are:

Operation Cost
O(1)
O(1)
O(n)
We can do better 
O(1)
O(1)

22
 A heap is a tree satisfying Heap-Order Property (HOP)
 For every node v other than the root, the value stored at v is
greater than or equal to value at v’s parent
I’m not a
I’m a heap  heap 

 Equivalently, any path from root to a leaf is sorted in ascending


order
 Minimum element is always at root  23
 A binary heap is a complete binary tree satisfying Heap-
Order property I’m a not
binary heap 
I’m a binary
I’m a binary heap 
heap 

 Height for a complete binary tree with n elements is


1+⌊log2(n)⌋ hence it is minimal
24
 Want to add a new element to a Binary Heap so that
result is also a Binary Heap

25
 Insertion:
 Place new element at next free position: Resulting tree
▪ to the right of last node in last level or is complete 
▪ at left of new level if last level was already full
 While new element value is less than its parent:
▪ Swap new element and its parent

26
 Insertion:
 Place new element at next free position:
▪ to the right of last node in last level or
▪ at left of new level if last level was already full
Resulting tree
 While new element value is less than its parent:
satisfies HOP 
▪ Swap new element and its parent

3
0

27
 Insertion:
 Place new element at next free position:
▪ to the right of last node in last level or
▪ at left of new level if last level was already full
Resulting tree
 While new element value is less than its parent:
satisfies HOP 
▪ Swap new element and its parent

3
0

0
3

28
 Insertion:
 Place new element at next free position:
▪ to the right of last node in last level or
▪ at left of new level if last level was already full
Resulting tree
 While new element value is less than its parent:
satisfies HOP 
▪ Swap new element and its parent
I’m a binary
heap 

0
1

3
0
1
0
3 3

29
 Recall that a complete tree with n elements
has 1+⌊log2(n)⌋ levels 500

450

400 n
 In the worst case, insertion 350

does ⌊log2(n)⌋ swaps 300

swaps
250
Huge difference
between n and log n
200

 So, insertion is O(log n)  150

100

50
log n
0

elements
30
 Want to remove element at the root of a Binary Heap
(smallest element) so that result is also a Binary Heap

5 7 6

31
 Let minChild(n) be the child of node n with minum value
▪ It can be the left child or the right one

 Deletion of root: Resulting tree is


also complete 
 Move rightmost element in last level to root of tree
 While value of this element is greater than its minChild value:
▪ Swap minChild and element

5 4
5 4 6

32
 Let minChild(n) be the child of node n with minum value
▪ It can be the left child or the right one

 Deletion of root:
 Move last element on last level to root of tree
Resulting tree is
 While value of this element is greater than its minChild value: satisfies HOP 
▪ Swap minChild and element

2 3
5 4
5 4 6

33
 Let minChild(n) be the child of node n with minum value
▪ It can be the left child or the right one

 Deletion of root:
 Move rightmost element in last level to root of tree
Resulting tree is
 While value of this element is greater than its minChild value: satisfies HOP 
▪ Swap minChild and element

7 2

2 3 7
5 4
5 4 6 5 4 6

34
 Let minChild(n) be the child of node n with minum value
▪ It can be the left child or the right one

 Deletion of root:
 Move rightmost element in last level to root of tree
Resulting tree is
 While value of this element is greater than its minChild value: satisfies HOP 
▪ Swap minChild and element

7 2

7
5 4
5 4 6 5 4 6

35
 Let minChild(n) be the child of node n with minum value
▪ It can be the left child or the right one

 Deletion of root:
 Move rightmost element in last level to root of tree
Resulting tree is
 While value of this element is greater than its minChild value: satisfies HOP 
▪ Swap minChild and element
I’m a binary
heap 

7 2 2

7 4
5 4
5 4 6 5 4 6 5 7 6

36
 Elements for a complete binary tree can easily be stored into an array by
levels:
Level 0 0 1 2 3 4 5 6

Level 1
Level 0 Level 1 Level 2

Level 2

children

Parents and children can be easily located:


• Root is at index 0 1 2 3 4 5 6
• For node at index i:
• its left child is at index i
• its right child is at index i
• its parent is at index ⌊ ⌋
parent
37
Elements in heap should provide an
order relation by implementing
method. must be
comparable to one of its supertypes

38
Elements in heap should
provide an order relation by
implementing
method

39
40

41
42
Minimum element is
always at root of
heap 

43
44
 The running costs for are:

Operation Cost
O(1)
O(1)
O(1) O(n) if array size
has to be doubled
O(log n)
O(log n)

45
46
Trivial Implementation:
all methods delegate on
corresponding heap method
Would this implementation work
properly if two or more elements with
same priorities were enqueued?

47
 Experimental test

 We measured execution time for doing 100000


random operations ( or ) on a
initially empty priority queue.

 Using an Intel i7 860 CPU:


 Binary Heap is about 150 times faster than Linear
Linked priority queue 

48
 Let weight of a node be the number of elements in the tree rooted at that node

 We will represent a heap by means of an augmented binary tree: every node


holds, in addition to its value and (left and right) children, its weight:

Weight for this


node

Tree rooted at
has elements

Tree rooted at
has elements

49
 A tree is Weight Biased Leftist if, for any node in tree, weight of its
left child is greater than or equal to weight of right child

 A Weight Biased Leftist heap (WBLH) is a Weight Biased Leftist tree


satisfying Heap-order property
I’m a WBLH I’m a WBLH I’m a WBLH
  

50
 Let right spine of a binary tree be path from root to
rightmost empty subtree Right spine

 For any WBLT with n elements,


length of its right spine ≤ ⌊log2(n+1)⌋

Will be used to make merge a logarithmic operation

51
 Two WBLHs with 50 random elements. Note short length of right
spines:

52
 For any WBLT with n elements,
length of its right spine ≤ ⌊log2(n+1)⌋

 Base case:
⌊ ⌋

 Inductive step:
Let = and =

if ⌊ ⌋ ⌊ ⌋
then ⌊ ⌋

53
 Base case:

⌊ ⌋

⌊ ⌋

54
 Inductive step:
Let = and =
if ⌊ ⌋ ⌊ ⌋
then ⌊ ⌋ Induction
Hypothesis

⌊ ⌋

⌊ ⌋

⌊ ⌋ ⌊ ⌋
⇐ ⌊ ⌋ ⌊ ⌋ ⌊ ⌋
⌊ ⌋ ⌊ ⌋
⇐ ∙
⌊ ⌋ ⌊ ⌋
⇐ ⌊ ⌋ ⇒ ⌊ ⌋ ⌊ ⌋ ⇒

55
 We want to obtain a new WBLH by merging two
WBLHs
1

 We want to do this efficiently:


 By merging both heaps along their right spines (O(log n))

56
 We want to merge two already sorted lists to obtain a new sorted list

57
 Auxiliary function constructing a from two WBLHs and a value:

puts always heavier


heap on left side

Enforces weight
Result is always weight biased leftist invariant
biased leftist, but it is not
necessarily heap ordered

58
Enforces weight
biased leftist and
heap-order invariants

59
Enforces weight
biased leftist and
heap-order invariants

Heavier heap on
left side
1

60
Enforces weight
biased leftist and
heap-order invariants

1 1

61
Enforces weight
biased leftist and
heap-order invariants

1 1

62
Minimum element is
at root of heap

Remove root and


merge left and right
children

Create a one element


heap and merge it into
our heap

63
root

Stands for

64
Enforces weight
biased leftist invariant

65
private static <T extends Comparable<? super T>>
Tree<T> merge(Tree<T> h1, Tree<T> h2) {

if (h1 == null)
return h2;
Enforces weight
if (h2 == null) biased leftist and
return h1; heap-order invariants
T x1 = h1.elem;
T x2 = h2.elem;
if (x1.compareTo(x2) <= 0) { // x1 <= x2
return node(x1, h1.left, merge(h1.right, h2));
} else {
return node(x2, h2.left, merge(h1, h2.right));
}
}

66
Memory efficient alternative
implementation of :
reuses old nodes

67
Minimum element is
at root of heap

Remove root and


merge left and right
children

Create a one element


heap and merge it into
our heap

68
 The running costs are:

Operation Cost
O(1)
O(1)
O(1)
O(log n)
O(log n)
O(log n)

69
 Experimental test

 We timed execution time for doing 100000


random operations ( or ) on a
initially empty priority queue.

 Using an Intel i7 860 CPU:


 Binary Heap is about 150 times faster than Linked
Queue
 WBLH is about 290 times faster than Linked Queue 
 WBLH is about 2 times faster than Binary Heap 
70
71
Build singleton heap with
each element

Do until
obtaining a single heap

heaps pairwise

 Let T(n) be number of evaluation steps for on a list with n elements:


 T(n) = n/2 ∙ O(log2 1) + n/4 ∙ O(log2 2) + n/8 ∙ O(log2 4) + … + 1 ∙ O(log2 (n/2))
n/2 merges of 1
element heaps n/4 merges of 2 n/8 merges of 4 1 merge of n/2
elements heaps elements heaps elements heaps

 Solution is T(n) = O(n) 

72
is O(n ∙ log n)

n deletions each one


taking O(log n) steps
O(n) for

73
 Binary Search Tree (BST): is a binary tree such that for any node v,
 All elements in left subtree are
less than element at v, and
 All elements in right subtree are
greater than element at v

Order Invariant

74
 We want to insert a new element into a BST so that a
new BST is obtained (maintains Order Invariant)

75
 We want to insert a new element into a BST so that a
new BST is obtained (maintains Order Invariant)

7
7 should be on right of 4

76
 We want to insert a new element into a BST so that a
new BST is obtained (maintains Order Invariant)

7
7 should be on left of 8

77
 We want to insert a new element into a BST so that a
new BST is obtained (maintains Order Invariant)

7 should be on right of 6

78
 We want to insert a new element into a BST so that a
new BST is obtained (maintains Order Invariant)

7 should go here

79
 We want to insert a new element into a BST so that a
new BST is obtained (maintains Order Invariant)

80
 Performance is proportional to height of tree. For a tree with n elements:

Good case: is O(log n) 


Worst case: is O(n) 

Height is O(log n)
Height is O(n)

81
 Two BSTs with random elements. Note that trees are mostly balanced:

82
 Inserting ordered elements into a BST leads to degenerated trees:

83
 In-order traversal for BSTs returns tree elements
in sorted order (tree sort algorithm)
Creates a BST by inserting
all elements in list

84
search search

Maybe

85
 Minimum element is at leftmost position (at end of left
spine):

Minimum
element

86
 Maximum element is at rightmost position (at end of
right spine):

Maximum
element

87
 First, node should be located using same algorithm as insertion
 If node to delete is a leaf, it can be just removed.
Resulting tree is a BST
Maintains Order Invariant

'c'

leaf

88
 First, node should be located using same algorithm as insertion
 If node to delete has only one child, parent node can be
connected to that child.
Resulting tree is a BST Maintains Order Invariant

Only 1 child

‘b'

89
 First, node should be located using same algorithm as insertion
 If node to delete has two children:
 Minimum element at right child of node to be deleted should replace
deleted element. Maintains Order Invariant
Resulting tree is a BST

2 children

‘d'

right child
Minimum at
right child

90
 First, node should be located using same algorithm as insertion
 If node to delete has two children:
 Alternatively: maximum element at left child of node to be deleted should
replace deleted element. Maintains Order Invariant
Resulting tree is a BST

2 children

‘d'

Left child
Maximum at
left child

91
 Removes and returns minimum element from non-empty tree:

92
One child is empty

Minimum Right tree without


element on minimum element All elements in lt are smaller
right tree tan those in rt hence x’is
greater than elements in lt

93

94
 The worst case running costs are:

Operation Cost
O(1)
O(1)
O(n)
O(n)
O(n)
O(n)
O(n)

 Many operations are O(log n) if trees are balanced


95
Keys should provide an order
relation by implementing
method

We will implement a variant in which


each node in the search tree keeps two
items of information: a key ( ) and a
value ( ).

Nodes in tree are sorted according to


their keys.

96
97
Returns value for node with key
, or if key is not in tree

Recall tree is sorted


according to key values

Returns if tree includes a


node with key

98
Inserts node with and
in tree. If node with key
was already present, value is
replaced.

99
100
Deletes node with
and in tree.

Remove min elem in


, but copying
its contents to before
101
Returns an iterator that
yields keys in tree when
traversed in-order
Prints:
and

are also available

102
is
. Can be iterated
using loop

Prints:

and

are also s

103
 Experimental test

 We timed execution time for doing 50000


random operations ( , , or )
on a initially empty set.

 Using an Intel i7 860 CPU:


 BST is 256 times faster than Linked Sorted Set 

104
 Operations on BST are O(log n) if tree is balanced
but can degrade to O(n)

 Height balanced trees keep their height small in


the face of arbitrary item insertions and
deletions, avoiding degradation of performance
http://en.wikipedia.org/wiki/Self-balancing_binary_search_tree

 Popular approaches to balanced trees are:


 AVL trees
 2-3 and 2-3-4 trees
 Red-Black trees
105
http://en.wikipedia.org/wiki/AVL_tree

 Named after its two soviet inventors,


Adelson-Velskii and Landis:

 "An algorithm for the organization of information“ (1962)

 AVL tree is a Binary Search Tree satisfying height-balance property:


For every node, heights of left and right children differ by at most one

These are all AVL trees


106
4
Height of tree rooted
at this node Height
2 3

1 1 2 2

0 0 0 0 1 1 0 1

0 0 0 0 0 0

107
 Two AVL trees with 50 random elements:

108
 Height of AVL tree with n elements is O(logϕ n)

 Let N(h) be minimum number


of nodes in an AVL of height h:

N(1) = 1
AVL trees with min number of nodes for heights 1,2 and 3
N(2) = 2
N(h) = 1 + N(h - 1) + N(h - 2) , h > 2
Height for one Difference for children
Node on root of heights ≤ 1
child should be
tree with height h
h -1

N(h) = O(ϕh) hence h = O(logϕ n)


1+ 5
ϕ=
2
109
 Constructs a new node from two AVL trees and a value

 Computes height of new node

2 2

110
 A rotation is an operation that changes the
structure of a binary search tree without violating
the order invariant

 A rotation moves one node up and another node


down. One subtree is detached from the node
moved up and attached to the node moved down

 Rotations can be used to rebalance binary search


trees, resulting in improved performance for
some operations
111
7 3

3 9 0 7

0 5 5 9

112
Maintains Order Invariant

7 3

3 7
Less
Greater
than 3
than 7

Greater Greater
Less than 3 and than 3 and Greater
than 3 less than 7 less than 7 than 7

113
3 7

0 7 3 9

5 9 0 5

114
Maintains Order Invariant

3 7

7 3
Less
Greater
than 3
than 7

Greater Greater
than 3 and Greater Less
than 3 and
less than 7 than 7 than 3 less than 7

115
 Testing balance of AVL trees:

116
This is anA
VLtree h

h+1

h+2

After insertion on These are not


left child, left child A
VLtrees
h anymore 
leans left
1
h+1

h+2

h
Can be rebalanced
with a single rotation h+1

h+2
117
h
This is anA
VLtree
h+1

h+2

These are not


After insertion on
A
VLtrees
right child, right child
h anymore 
leans right
1
h+1

h+2

Can be rebalanced h
with a single rotation
h+1

h+2 118
h
This is anA
VLtree
h+1

h+2

After insertion on These are not


left child, left child A
VLtrees
h leans right anymore 
1
h+1

h+2

h
Can be rebalanced
with a double rotation h+1

h+2
119
h
This is anA
VLtree
h+1

h+2

These are not After insertion on


A
VLtrees right child, right child
h
anymore  leans left
1
h+1

h+2

Can be rebalanced h
with a double rotation h+1

h+2
120
After insertion on
left child, left child
leans left

Right rotation
h h

h+1 2 h+1

h+2 h+2

121
After insertion on
right child, right
child leans right

Left rotation
h h

h+1 2 h+1

h+2 h+2

122
After insertion on
left child, left child
leans right

h
h
h+1 2
h+1
h+2
Only one of these h+2
trees can get to h+2

Left rotation on h
left subtree ( )
h+1
Right rotation
h+2 on root 123
After insertion on
right child, right
child leans left

h
h
h+1 2
h+1
h+2
Only one of these h+2
trees can get to h+2

Right rotation on h
right subtree ( )
h+1
Left rotation
h+2 on root 124
 Just like insertion into Binary Search trees, but check if
balance should be restored for any modified node:

Only nodes in path from root to point


of insertion are modified and may need
to be rebalanced

125
No need to
rebalance 1 0

126
No need to
rebalance 2 1

127
Single rotation
needed

Leans left 3 1

128
This is anA
VLtree

129
No need to
rebalance 0 1

130
No need to
rebalance 1 2

131
Double rotation
needed

Leans right 3 1

132
left child

133
left child

This is anA
VLtree

134
search search
 Just like Binary Search Trees:

Maybe

135
 Just like deletion for Binary Search trees, but check if
balance should be restored for any modified node:

136
 The running costs are:

Operation Cost
O(1)
O(1)
O(log n)
O(log n)
O(log n)
O(log n)
O(log n)

137
 Experimental test. Elements inserted in random
order.

 We timed execution time for doing 50000


random operations ( , , or )
on a initially empty set.

 Using an Intel i7 860 CPU:


 BST is 256 times faster than Linked Sorted Set 
 AVL is 192 times faster than Linked Sorted Set 
 BST is 1.33 times faster than AVL on random data
138
 Experimental test: Elements inserted in ascending
order. (degenerated BST)

 We timed execution time for doing 50000


random operations ( , , or )
on a initially empty set with.

 Using an Intel i7 860 CPU:


 BST is 2.5 times slower than Linked Sorted Set 
 AVL is 172 times faster than Linked Sorted Set 
 AVL is 444 times faster than BST on sorted data
139
Context for and
may be si se usa el
orden de las claves
140
141
 A Dictionary can efficiently be implemented by using a
balanced search tree with keys and values in nodes

 Tree should be sorted according to key values

Key V
alue

142
Each node in tree stores a
( :-> )

Two s are equal if


their keys are equal

Nodes in tree will be


sorted according to
their keys 143
Simple Implementation:
all operations delegate on
corresponding AVL trees
operation

144
 Using a balanced search tree, the running costs
are:

Operation Cost
O(1)
O(1)
O(log n)
O(log n)

145
Student may study next slides at home in order to go deeper into the subject

146
 A 9x9 grid
 Nine 3x3 sub-grids
 You should complete grid with numbers in 1 to 9
 All numbers in a row should be different
 All numbers in a column should be different
 All number in a sub-grid should be different

147
rows and
columns

in a cell means it is free

148
returns element at index in list :

0 1 2 3 4 5 6 7 8
0
1
2
3
4
5
6
7
8

149
 Nodes will be (possible incomplete) sudokus
 We will fill free cells in left to right order from first row to last one
 Children of a Sudoku are those obtained by completing with a compatible value next free cell

45

A Tree with
46 sudokus

49
6

 We aim to find a totally completed sudoku starting from the inital one
150
See full code in Sudoku.hs file

Try to assign all values to cell,


but keep only compatible ones

151
pre-order traversal of tree

Return only first Keep only complete Traverse tree in preOrder


solution (solutions) sudokus in tree

152
 Let be a list of elements
 We want to construct a binary tree so that:
 Heigth of is minimal
 And

153
Test correctness for

154
 Let T(n) be number of evaluation steps for on a list with n elements:
 T(n) = 1, if n < 2
 T(n) = O(n) + 2 T(n/2), if n ≥ 2

is O(n)

 Solution is T(n) = O(n ∙ log n) 

155
returns tree with
first n elements in xs and
rest of the list ( ).
We are solving a more
general problem

 Let T(n) be number of evaluation steps for on a list with n elements:


 T(n) = 1, if n < 2
 T(n) = O(1) + 2 T(n/2), if n ≥ 2

 Solution is T(n) = O(n) 

156
 On iterator construction on stack root
T be visited elements are
o
kept in reverse order in the
stack, as stack is LIFO

Visit right subtree thirdly

Visit key secondly

Visit left subtree firstly

A stack will be used to keep yet to be visited elements.

Stack will hold two types of values:


• Trees
• Or keys

stack 157
stack 158
stack 159
stack 160
stack 161
stack 162
stack 163
stack 164
stack 165
stack 166
stack 167
stack 168
stack 169
stack 170
stack 171
stack 172
stack 173
stack 174
stack 175
stack 176
 Stack must be able to hold two types of values: trees and keys.
 Object with type can hold
 A value of type (a left value)
 Or either a value of type (a right value)

if holds holds
an

gets in

holds

if holds
a

gets in 177
178
can hold either a
Will be defined for each key (left value) or a tree
traversal: inOrder, (right value)
Initialize stack preOrder and postOrder

No more elements if
stack is empty

While it is a tree

It is a key

179
An anonymous class
extending class

Visit right
subtree thirdly

Visit key secondly

Visit left subtree


firstly

180
Visit right
subtree thirdly
Visit left subtree
secondly

Visit key firstly

181
Visit key thirdly

Visit right subtree


secondly

Visit left subtree


firstly

182
We will implement a variant in which
each node in the tree keeps two items
of information: a key and a value.

Nodes in tree are sorted according to


their key values.

183
184
7 3

3 9 0 7

0 5 5 9

185
3 7

0 7 3 9

5 9 0 5
186
187
 Just like Binary Search Trees:

188
 Just like insertion into Binary Search trees, but check if balance
should be restored for any modified node:

189

You might also like