building blocks of software
Post on 04-May-2022
1 Views
Preview:
TRANSCRIPT
Building Blocks of Software
Units 7 & 8 Tutorial
Session: 13 January 2010
Printed: 13th January 2010
Agenda
1. Main points about Unit 7 The Class Set and Unit 8 Binary Trees. Mainly concentrate on trees since
last tutorial covered Units 5, 6 and a bit of sets.
2. Some questions similar to TMA02 Qs 5–8
3. Turning the English strategy into code — this would include some or all of:
Binary Tree COMPLETE_TREE, LEVEL_ORDER, IN_ORDER, GROW_TREE
Binary Search Tree INSERT_TREE, SEARCH_TREE
Heap addHeap (Strategy 3.3), removeRootHeap (3.4), heapSort (Activity 3.7).
4. Unit 8 mentions deleting the root of a heap but not deleting the root of a binary search tree — we
will investigate the choices when deleting an item.
5. Using tree diagrams to investigate algorithms — dealing with the cases of the EmptyTree, Node,
Node with non-empty subtrees and so on.
6. Investigating some of the features of WorkPad.
1
2 Building Blocks of Software M263 2009/2010
Exercises
1. Sets — Unit 7
Suppose C and D are the following sets of integers:
C = {2,1,2,3,4,3}
D = {3,4,5,6}
(a) Evaluate the following:
i. C ∪ D
ii. C ∩ D
iii. {} ∈ C
iv. C == {1,2,3,4}
v. {} ⊆ C
vi. {} ⊆ {}
vii. C − D
viii. C ⊆ (C ∪ D)
ix. C ⊆ (C ∩ D)
x. powerset(C)
xi. cardinality(powerset(C))
xii. powerset({})
(b) Evaluate the following set expressions, where A, B are members of Image or SetOfGrid
i. A = {(x,y) in Pair of Int: x − y ≥ 1}
ii. B = {(x,y) in Pair of Int: x == 3 ∨ y == 2}
iii. A∪ B
iv. A∩ B
2. Binary Trees — Unit 8, Section 1
(a) Suppose that t is a binary tree of integers (that is, an object of type BinTree of Int) in the state
shown below:
3
9
24
46 71
31
77
21
37 70
Write down the value returned by each of the method calls below:
i. t.getDepth()
ii. t.leftTree().rightTree().getDepth()
iii. t.rightTree().rightTree().getRoot()
Building Blocks of Software M263 Units 7 & 8 Tutorial 3
Draw the binary trees returned by each of the method calls below:
iv. t.leftTree()
v. t.rightTree()
vi. t.leftTree().leftTree().rightTree()
(b) A function REPLACE_LEFT is specified below:
function REPLACE_LEFT(t in BinTree of Int, s in BinTree of Int)
return in BinTree of Int
pre t is not empty
post The returned value is a binary tree that has the same root and right tree as t and whose
left subtree is s
i. If t is the tree in the first part of the question above and s is given below, draw the value
returned by REPLACE_LEFT(t,s)
6
41 33
ii. Give an implementation of REPLACE_LEFT
iii. Use the WorkPad to test your implementation of REPLACE_LEFT for the input values given
in (i)
3. Binary Trees — Unit 8, Sections 2 & 3
(a) Given the tree t, a binary tree of integers in the following state:
3
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 21
37 F G 70
Give the vectors returned by the following expressions:
i. LEVEL_ORDER(t)
ii. IN_ORDER(t)
(b) Evaluate SEARCH_TREE(v) where v is the vector given by the following code:
var v in Vector of Intv.setVector(77,11,12,30,99,97,13,5)
(c) The tree t above is a heap tree. Use Strategy 3.4 of Unit 8 to remove the root item from the
tree — draw the resulting tree and use the same labelling system as the original heap.
(d) Use Strategy 3.3 of Unit 8 to add the integer 2 to the original tree t above and draw the resulting
tree with labels
4 Building Blocks of Software M263 2009/2010
4. Binary Trees — Unit 8, Section 1
Write a function HEIGHT which takes a tree and returns its height (also called depth)
5. Binary Trees — Unit 8, Section 1
Define a function called numLeaves which takes a tree and returns the number of leaves — that is
the number of nodes with both subtrees empty.
6. Binary Trees — Unit 8, Section 1
Define a function fringe which takes a binary tree and outputs a vector of the items at the leaves.
7. Binary Trees — Unit 8, Section
Implement IN_ORDER, GROW_TREE and LEVEL_ORDER
8. Binary Search Trees — Unit 8, Section 3
Implement INSERT_TREE , insertListBST which takes a binary search tree and a list of items and
returns a new tree with the items inserted.
Implement SEARCH_TREE — hint: use insertListBST and IN_ORDER to sort the list.
9. Implement deleteBST which takes an item and a Binary Search Tree and deletes the item (if present)
and returns a properly formed Binary Search Tree.
Author: Phil Molyneux (with Alex McGuiggan, Claudi Thomas, Tim Lister)Session: 13 January 2010 Printed: 13th January 2010Source: <baseURL>OU/M263/tutorialU7U82009J.pdf
Building Blocks of Software M263 Units 7 & 8 Tutorial 5
Solutions
1. Sets — Unit 7
△ Indicative Answer:
(a) i. {1,2,3,4,5,6}
ii. {3,4}
iii. false
iv. true
v. true
vi. true
vii. {1,2}
viii. true
ix. false
x. {{},{1},. . . ,{1,2,3,4}}
xi. 16 == 24
xii. {{}}
(b) i. A == {(2,1),(3,1),(4,1),(3,2),(4,2),(4,3)}
ii. B == {(1,2),(2,2),(3,2),(4,2),(3,1),(3,3),(3,4)}
iii. A∪ B
iv. A∩ B
End △
2. Binary Trees — Unit 8, Section 1
△ Indicative Answer:
(a) i. 4
ii. 2
iii. 70
iv. 9
24
46 71
31
77
v. 21
37 70
6 Building Blocks of Software M263 2009/2010
vi. 71
(b) i. 3
6
41 33
21
37 70
ii. There are several alternatives:
Beginning of code
1 function REPLACE_LEFT(t,s){2 var outTree in BinTree of Int3 outTree <-- t.clone()4 outTree.setLeftTree(s)5 return outTree6 }
End of code
Beginning of code
1 function REPLACE_LEFT(t,s){2 var outTree in BinTree of Int3 outTree.setTree(t.getRoot(), s, t.rightTree())4 return outTree5 }
End of code
End △
3. Binary Trees — Unit 8, Section 2 & 3
△ Indicative Answer:
(a) i. [3,9,21,24,31,37,70,46,71,34,77]
ii. [46,24,71,9,34,31,77,3,37,21,70]
(b) 30
12
11
5
13
97
77 99
(c) In the steps of the strategy:
A. (steps 1 & 2) Replace root by last leaf:
Building Blocks of Software M263 Units 7 & 8 Tutorial 7
77
A
9 B
24 D
46 H I 71
E 31
34 J
C 21
37 F G 70
B. (step 4) Swap 77 with 9
9
A
77 B
24 D
46 H I 71
E 31
34 J
C 21
37 F G 70
C. (step 4) Swap 77 with 24
9
A
24 B
77 D
46 H I 71
E 31
34 J
C 21
37 F G 70
D. (steps 4 & 5) Swap 77 with 46 and stop since no more child nodes below
8 Building Blocks of Software M263 2009/2010
9
A
24 B
46 D
77 H I 71
E 31
34 J
C 21
37 F G 70
(d) In the steps of the strategy:
A. (step 1) Add a node, L, with the item 2 as the left child of node F:
3
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 21
37 F
2 L
G 70
B. (step 2) Swap 2 on node L with 37 on node F
3
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 21
2 F
37 L
G 70
C. (step 2) Swap 2 on node F with 21 on node C
Building Blocks of Software M263 Units 7 & 8 Tutorial 9
3
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 2
21 F
37 L
G 70
D. (steps 2 & 4) Swap 2 on node C with 3 on node A and stop since no more parent nodes
above
2
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 3
21 F
37 L
G 70
End △
4. Binary Trees — Unit 8, Section 1
△ Indicative Answer: Strategy: use the definition of height and the recursive nature of trees
Beginning of code
1 function HEIGHT(t){2 var h in Int3 if (t.isEmpty())4 then {return 0}5 else {return 1 + maxInt(HEIGHT(t.leftTree()),HEIGHT(t.rightTree()))}6 }
End of code
maxInt needs to be written. End △
5. Binary Trees — Unit 8, Section 1
△ Indicative Answer:
Beginning of code
1 function numLeaves(t){2 var n in Int3 if (t.isEmpty()) then {return 0}4 else if (t.leftTree().isEmpty() /\ t.rightTree().isEmpty())5 then {return 1}6 else {return numLeaves(t.leftTree()) + numLeaves(t.rightTree())7 }
10 Building Blocks of Software M263 2009/2010
End of code
End △
6. Binary Trees — Unit 8, Section 1
△ Indicative Answer:
Beginning of code
1 function fringe(t){2 var f in VectorPlus of X3 if (t.isEmpty()) then {return f}4 else if (t.leftTree().isEmpty() /\ t.rightTree().isEmpty())5 then {return f.setVector(t.getRoot())}6 else {return fringe(t.leftTree()).join(fringe(t.rightTree()))7
8 }
End of code
OK, I ended up using VectorPlus of X because join is not in Vector of X — but notice how the tree
structure drives the definition? End △
7. Binary Trees — Unit 8, Section
Implement IN_ORDER, GROW_TREE and LEVEL_ORDER
8. Binary Search Trees — Unit 8, Section 3
Implement INSERT_TREE , insertListBST which takes a binary search tree and a list of items and
returns a new tree with the items inserted.
Implement SEARCH_TREE — hint: use insertListBST and IN_ORDER to sort the list.
9. Implement deleteBST which takes an item and a Binary Search Tree and deletes the item (if present)
and returns a properly formed Binary Search Tree.
△ Indicative Answer:
Implement deleteBST which takes an item and a Binary Search Tree and deletes the item (if present)
and returns a properly formed Binary Search Tree.
Here is an example Binary Search Tree (with H to delete):
H
D
B
A C
F
E G
L
J
I K
N
M O
Here is our starting strategy — it is driven by the structure of trees:
Beginning of code
1 function deleteBST(x,t){2 var newT in BinTree of Int // new empty tree3 if (t.isEmpty()) then {return newT}4 else if (x < t.getRoot())5 then {return newT.setTree(t.getRoot(),6 deleteBST(x,t.leftTree()),7 t.rightTree())}8 else if (x > t.getRoot())9 then {return newT.setTree(t.getRoot(),
10 t.leftTree(),
Building Blocks of Software M263 Units 7 & 8 Tutorial 11
11 deleteBST(x,t.rightTree())}12 else {return joinBST(t.leftTree(), t.rightTree())}13 }
End of code
All we have to do is define joinBST — but we have a lot of choices — our aim will be to keep the tree
as “flat” as possible — since that makes searches more efficient:
Method A
We could just use function we already have to list out all the elements of the left subtree (using
IN_ORDER) and insert the resulting vector in the right subtree using insertListBST .
Beginning of code
1 function joinBSTA(leftT,rightT){2 var newT in BinTree of Int3 if (leftT.isEmpty())4 then {newT <-- rightT.clone()}5 else {newT <-- insertListBST(rightT, (IN_ORDER(leftT)))}6 return newT7 }
End of code
However this is not a good strategy since we end up with a high tree:
Method A — Deleting the Root of a BST
12 Building Blocks of Software M263 2009/2010
L
J
I
A
B
C
D
E
F
G
K
N
M O
Method B
Method A made no use of our knowledge of the original tree — we know:
maxItem(leftT) < minItem(rightT)
So we could just hang the whole right tree off the rightmost (or largest) item in the left tree:
Beginning of code
1 function joinBSTB(leftT,rightT){2 var newT in BinTree of Int3 if (leftT.isEmpty())4 then {newT <-- rightT.clone()}5 else {newT.setTree(leftT.getRoot(),6 leftT.leftTree(),7 joinBSTB(leftT.rightTree(),rightT))}8 return newT9 }
End of code
Building Blocks of Software M263 Units 7 & 8 Tutorial 13
D
B
A C
F
E G
L
J
I K
N
M O
Method C
Method B is not as good as it could be — we have deleted an item but still increased the height —
we can make better use of our knowledge of the tree. We can promote the maximum item in the left
subtree to be the new root for the combined tree:
Beginning of code
1 function joinBSTB(leftT,rightT){2 var newT in BinTree of Int3 if (leftT.isEmpty())4 then {newT <-- rightT.clone()}5 else {6 var m in Int7 m <-- maxItemBST(leftT)8 newT.setTree(m,9 deleteBST(m,leftT),
10 rightT)11 }12 return newT13 }14
15 function maxItemBST(t){16 // Precondition: t is not empty and is BST17 var x in Int18 if (t.rightTree().isEmptyTree())19 then {x <-- t.getRoot()}20 else {x <-- maxItemBST(t.rightTree())}21 return x22 }
End of code
This gives a compact tree:
14 Building Blocks of Software M263 2009/2010
G
D
B
A C
F
E
L
J
I K
N
M O
The code could be made more efficient by finding the max item and removing it in one traversal of
the tree using lazy evaluation from the functional programming bag of tricks but we shall leave that
for another course (drawing the tree diagrams was hard enough!)
Author: Phil Molyneux (with Alex McGuiggan, Claudi Thomas, Tim Lister)Session: 13 January 2010 Printed: 13th January 2010Source: <baseURL>OU/M263/tutorialU7U82009J.pdf
M263 Unit 7 and Unit 8 Tutorial
Agenda
1. Main points about Unit 7 The Class Set and Unit 8 Binary Trees. Mainly
concentrate on trees since last tutorial covered Units 5, 6 and a bit of
sets.
2. Some questions similar to TMA02 Qs 5–8
3. Turning the English strategy into code — this would include some or
all of:
Binary Tree COMPLETE_TREE, LEVEL_ORDER, IN_ORDER, GROW_TREE
Binary Search Tree INSERT_TREE, SEARCH_TREE
Heap addHeap (Strategy 3.3), removeRootHeap (3.4), heapSort (Activ-
ity 3.7).
4. Unit 8 mentions deleting the root of a heap but not deleting the root
of a binary search tree — we will investigate the choices when deleting
an item.
5. Using tree diagrams to investigate algorithms — dealing with the cases
of the EmptyTree, Node, Node with non-empty subtrees and so on.
6. Investigating some of the features of WorkPad.
1
Unit 7 Sets
• Set notation, Membership and subsets
• Set operations
• The class Set — WorkPad
• Set comprehension — some programming languages (Miranda, Haskell. . . )
provide list comprehensions as a built-in expression which gives a nice
notation for common iterations over lists.
2
Exercises
Question 1
Sets — Unit 7
Suppose C and D are the following sets of integers:
C = {2,1,2,3,4,3}
D = {3,4,5,6}
(a) Evaluate the following:
i. C ∪ D
ii. C ∩ D
iii. {} ∈ C
iv. C == {1,2,3,4}
v. {} ⊆ C
vi. {} ⊆ {}
vii. C − D
viii. C ⊆ (C ∪ D)
ix. C ⊆ (C ∩ D)
x. powerset(C)
xi. cardinality(powerset(C))
xii. powerset({})
(b) Evaluate the following set expressions, where A, B are members of Image
or SetOfGrid
i. A = {(x,y) in Pair of Int: x − y ≥ 1}
ii. B = {(x,y) in Pair of Int: x == 3 ∨ y == 2}
iii. A∪ B
iv. A∩ B
3
Solution 1
Sets — Unit 7
△ Indicative Answer:
(a) i. {1,2,3,4,5,6}
ii. {3,4}
iii. false
iv. true
v. true
vi. true
vii. {1,2}
viii. true
ix. false
x. {{},{1},. . . ,{1,2,3,4}}
xi. 16 == 24
xii. {{}}
(b) i. A == {(2,1),(3,1),(4,1),(3,2),(4,2),(4,3)}
ii. B == {(1,2),(2,2),(3,2),(4,2),(3,1),(3,3),(3,4)}
iii. A∪ B
iv. A∩ B
End △
4
Unit 8 Binary Trees
• Tree diagrams used in lots of applications — some familiar, some for
efficiency of data manipulation.
• Binary Trees and the class BinTree of X
• A BinTree is either empty or a node with a data item and two subtrees.
• Binary trees and vectors, tree traversals, complete trees, level order (or
breadth first) traversal, in-order traversal and growing tree from vector
by division of the list.
• Sorted binary trees, binary search trees, heaps.
5
Tree Quiz
Define the following terms — some are not in M263 but you may be able
to guess the answers:
1. Parent node of a node in a tree
2. Child node of a node
3. Tree Root
4. Leaf
5. Siblings of a node
6. Ancestor of a node
7. Descendent of a node
8. Empty Tree
9. Subtree of a node
10. Level of a node
11. Depth or Height of a tree
12. Complete Tree
13. Full Tree
14. Binary Search Tree
15. Balanced Tree
16. Heap
6
Question 2
Binary Trees — Unit 8, Section 1
(a) Suppose that t is a binary tree of integers (that is, an object of type Bin-
Tree of Int) in the state shown below:
3
9
24
46 71
31
77
21
37 70
Write down the value returned by each of the method calls below:
i. t.getDepth()
ii. t.leftTree().rightTree().getDepth()
iii. t.rightTree().rightTree().getRoot()
Draw the binary trees returned by each of the method calls below:
i. t.leftTree()
ii. t.rightTree()
iii. t.leftTree().leftTree().rightTree()
7
Question 2 contd
Binary Trees — Unit 8, Section 1
(b) A function REPLACE_LEFT is specified below:
function REPLACE_LEFT(t in BinTree of Int, s in BinTree of Int)
return in BinTree of Int
pre t is not empty
post The returned value is a binary tree that has the same root and
right tree as t and whose left subtree is s
i. If t is the tree in the first part of the question above and s is given
below, draw the value returned by REPLACE_LEFT(t,s)
6
41 33
ii. Give an implementation of REPLACE_LEFT
iii. Use the WorkPad to test your implementation of REPLACE_LEFT for
the input values given in (i)
8
Solution 2
Binary Trees — Unit 8, Section 1
△ Indicative Answer:
(a) i. 4
ii. 2
iii. 70
iv. 9
24
46 71
31
77
v. 21
37 70
vi. 71
9
Solution 2 contd
Binary Trees — Unit 8, Section 1
(b) i. 3
6
41 33
21
37 70
ii. There are several alternatives:
Beginning of code
1 function REPLACE_LEFT(t,s){
2 var outTree in BinTree of Int
3 outTree <-- t.clone()
4 outTree.setLeftTree(s)
5 return outTree
6 }End of code
Beginning of code
1 function REPLACE_LEFT(t,s){
2 var outTree in BinTree of Int
3 outTree.setTree(t.getRoot(), s, t.rightTree())
4 return outTree
5 }End of code
End △
10
Question 3
Binary Trees — Unit 8, Sections 2 & 3
(a) Given the tree t, a binary tree of integers in the following state:
3
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 21
37 F G 70
Give the vectors returned by the following expressions:
i. LEVEL_ORDER(t)
ii. IN_ORDER(t)
(b) Evaluate SEARCH_TREE(v) where v is the vector given by the following
code:
var v in Vector of Int
v.setVector(77,11,12,30,99,97,13,5)
(c) The tree t above is a heap tree. Use Strategy 3.4 of Unit 8 to remove
the root item from the tree — draw the resulting tree and use the same
labelling system as the original heap.
(d) Use Strategy 3.3 of Unit 8 to add the integer 2 to the original tree t above
and draw the resulting tree with labels
11
Solution 3
Binary Trees — Unit 8, Section 2 & 3
△ Indicative Answer:
(a) i. [3,9,21,24,31,37,70,46,71,34,77]
ii. [46,24,71,9,34,31,77,3,37,21,70]
(b) 30
12
11
5
13
97
77 99
12
Solution 3
Binary Trees — Unit 8, Section 2 & 3 contd
(c) In the steps of the strategy:
A. (steps 1 & 2) Replace root by last leaf:
77
A
9 B
24 D
46 H I 71
E 31
34 J
C 21
37 F G 70
B. (step 4) Swap 77 with 9
9
A
77 B
24 D
46 H I 71
E 31
34 J
C 21
37 F G 70
13
Solution 3
Binary Trees — Unit 8, Section 2 & 3 contd
(c) contd
C. (step 4) Swap 77 with 24
9
A
24 B
77 D
46 H I 71
E 31
34 J
C 21
37 F G 70
D. (steps 4 & 5) Swap 77 with 46 and stop since no more child nodes
below
9
A
24 B
46 D
77 H I 71
E 31
34 J
C 21
37 F G 70
End △
14
Solution 3
Binary Trees — Unit 8, Section 2 & 3 contd
(d) In the steps of the strategy:
A. (step 1) Add a node, L, with the item 2 as the left child of node F:
3
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 21
37 F
2 L
G 70
B. (step 2) Swap 2 on node L with 37 on node F
3
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 21
2 F
37 L
G 70
15
Solution 3
Binary Trees — Unit 8, Section 2 & 3 contd
(d) contd
C. (step 2) Swap 2 on node F with 21 on node C
3
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 2
21 F
37 L
G 70
D. (steps 2 & 4) Swap 2 on node C with 3 on node A and stop since no
more parent nodes above
2
A
9 B
24 D
46 H I 71
E 31
34 J K 77
C 3
21 F
37 L
G 70
End △
16
Solution 4
Binary Trees — Unit 8, Section 1
△ Indicative Answer: Strategy: use the definition of height and the re-
cursive nature of trees
Beginning of code
1 function HEIGHT(t){
2 var h in Int
3 if (t.isEmpty())
4 then {return 0}
5 else {return 1 + maxInt(HEIGHT(t.leftTree()),HEIGHT(t.rightTree()))}
6 }End of code
maxInt needs to be written. End △
17
Solution 5
Binary Trees — Unit 8, Section 1
△ Indicative Answer:
Beginning of code
1 function numLeaves(t){
2 var n in Int
3 if (t.isEmpty()) then {return 0}
4 else if (t.leftTree().isEmpty() /\ t.rightTree().isEmpty())
5 then {return 1}
6 else {return numLeaves(t.leftTree()) + numLeaves(t.rightTree())
7 }End of code
End △
18
Solution 6
Binary Trees — Unit 8, Section 1
△ Indicative Answer:
Beginning of code
1 function fringe(t){
2 var f in VectorPlus of X
3 if (t.isEmpty()) then {return f}
4 else if (t.leftTree().isEmpty() /\ t.rightTree().isEmpty())
5 then {return f.setVector(t.getRoot())}
6 else {return fringe(t.leftTree()).join(fringe(t.rightTree()))
7
8 }End of code
OK, I ended up using VectorPlus of X because join is not in Vector of X —
but notice how the tree structure drives the definition? End △
19
Solution 9
△ Indicative Answer:
Implement deleteBST which takes an item and a Binary Search Tree and deletes
the item (if present) and returns a properly formed Binary Search Tree.
Here is an example Binary Search Tree (with H to delete):
H
D
B
A C
F
E G
L
J
I K
N
M O
Here is our starting strategy — it is driven by the structure of trees:
Beginning of code
1 function deleteBST(x,t){
2 var newT in BinTree of Int // new empty tree
3 if (t.isEmpty()) then {return newT}
4 else if (x < t.getRoot())
5 then {return newT.setTree(t.getRoot(),
6 deleteBST(x,t.leftTree()),
7 t.rightTree())}
8 else if (x > t.getRoot())
9 then {return newT.setTree(t.getRoot(),
10 t.leftTree(),
11 deleteBST(x,t.rightTree())}
12 else {return joinBST(t.leftTree(), t.rightTree())}
13 }End of code
20
Solution 9 contd
All we have to do is define joinBST — but we have a lot of choices — our
aim will be to keep the tree as “flat” as possible — since that makes searches
more efficient:
Method A
We could just use function we already have to list out all the elements of
the left subtree (using IN_ORDER) and insert the resulting vector in the right
subtree using insertListBST .
Beginning of code
1 function joinBSTA(leftT,rightT){
2 var newT in BinTree of Int
3 if (leftT.isEmpty())
4 then {newT <-- rightT.clone()}
5 else {newT <-- insertListBST(rightT, (IN_ORDER(leftT)))}
6 return newT
7 }End of code
However this is not a good strategy since we end up with a high tree:
21
Solution 9 contd
Method A — Deleting the Root of a BST
L
J
I
A
B
C
D
E
F
G
K
N
M O
22
Solution 9 contd
Method B
Method A made no use of our knowledge of the original tree — we know:
maxItem(leftT) < minItem(rightT)
So we could just hang the whole right tree off the rightmost (or largest) item
in the left tree:
Beginning of code
1 function joinBSTB(leftT,rightT){
2 var newT in BinTree of Int
3 if (leftT.isEmpty())
4 then {newT <-- rightT.clone()}
5 else {newT.setTree(leftT.getRoot(),
6 leftT.leftTree(),
7 joinBSTB(leftT.rightTree(),rightT))}
8 return newT
9 }End of code
D
B
A C
F
E G
L
J
I K
N
M O
23
Solution 9 contd
Method C
Method B is not as good as it could be — we have deleted an item but still
increased the height — we can make better use of our knowledge of the
tree. We can promote the maximum item in the left subtree to be the new
root for the combined tree:
Beginning of code
1 function joinBSTB(leftT,rightT){
2 var newT in BinTree of Int
3 if (leftT.isEmpty())
4 then {newT <-- rightT.clone()}
5 else {
6 var m in Int
7 m <-- maxItemBST(leftT)
8 newT.setTree(m,
9 deleteBST(m,leftT),
10 rightT)
11 }
12 return newT
13 }
14
15 function maxItemBST(t){
16 // Precondition: t is not empty and is BST
17 var x in Int
18 if (t.rightTree().isEmptyTree())
19 then {x <-- t.getRoot()}
20 else {x <-- maxItemBST(t.rightTree())}
21 return x
22 }End of code
This gives a compact tree:
24
Solution 9 contd
G
D
B
A C
F
E
L
J
I K
N
M O
The code could be made more efficient by finding the max item and remov-
ing it in one traversal of the tree using lazy evaluation from the functional
programming bag of tricks but we shall leave that for another course (draw-
ing the tree diagrams was hard enough!)
25
Producing the Tree Diagrams
The course documents are produced using the markup language LATEX with
some custom style files — for general information see The LATEX Project,
http://www.latex-project.org/ and The TEX User Group
http://tug.org — there are free implementations for MS Windows, Mac
OS X and Linux (and many other platforms)
The tree diagrams use the PSTricks set of extensions to LATEX — see
http://tug.org/PSTricks/
The LATEX markup for the tree diagram in Question 2 is
\begin{center}
\treeEGalexT
\end{center}
\treeEGalexT is a user-defined command built out of LATEX and PSTricks
commands:
% Include various PSTricks packages
\usepackage{pstricks,pst-node,pst-tree}
% Set the circle width command
\newlength{\OUcircleWidth}
\newcommand{\OUsetCircleWidth}[1]{%
\settowidth{\OUcircleWidth}{#1}%
}
% Augment the \Tcircle command to fix the circle width
\newcommand{\Tcc}[1]{%
\Tcircle{\makebox[\OUcircleWidth][c]{#1}}
}
% Create a tree with the circle width set dynamically
\newcommand{\treeEGalexT}{%
\OUsetCircleWidth{99}%
\pstree{\Tcc{3}}{
\treeEGalexTl \treeEGalexTr
}
}
% \treeEGalexTl and \treeEGalexTr are commands defined on the next slide
26
Producing the Tree Diagrams 2
The markup for trees is built up from subtrees so they can be reused:
\newcommand{\treeEGalexTl}{%
\OUsetCircleWidth{99}%
\pstree{\Tcc{9}}{
\treeEGalexTll \treeEGalexTlr
}
}
\newcommand{\treeEGalexTll}{%
\OUsetCircleWidth{99}%
\pstree{\Tcc{24}}{
\Tcc{46} \Tcc{71}
}
}
\newcommand{\treeEGalexTlr}{%
\OUsetCircleWidth{99}%
\pstree{\Tcc{31}}{
\Tn \Tcc{77}
}
}
\newcommand{\treeEGalexTr}{%
\OUsetCircleWidth{99}%
\pstree{\Tcc{21}}{
\Tcc{37} \Tcc{70}
}
}
27
Producing the Tree Diagrams 3
Here is the markup for the labelled tree in question 3
% Tree example for heap question --- based on alex tree
\newcommand{\Tcn}[3]{\Tcc{#1}~[tnpos=#2]{#3}}
\newcommand{\treeEGheapQ}{%
\OUsetCircleWidth{99}%
\pstree{\Tcn{3}{a}{A}}{
\treeEGheapQl
\treeEGheapQr
}
}
\newcommand{\treeEGheapQl}{%
\OUsetCircleWidth{99}%
\pstree{\Tcn{9}{r}{B}}{
\treeEGheapQll
\treeEGheapQlr
}
}
\newcommand{\treeEGheapQll}{%
\OUsetCircleWidth{99}%
\pstree{\Tcn{24}{r}{D}}{
\Tcn{46}{r}{H} \Tcn{71}{l}{I}
}
}
\newcommand{\treeEGheapQlr}{%
\OUsetCircleWidth{99}%
\pstree{\Tcn{31}{l}{E}}{
\Tcn{34}{r}{J} \Tcn{77}{l}{K}
}
}
\newcommand{\treeEGheapQr}{%
\OUsetCircleWidth{99}%
\pstree{\Tcn{21}{l}{C}}{
\Tcn{37}{r}{F} \Tcn{70}{l}{G}
}
}
28
Producing the Tutorial Document
Here is the start of the LATEX document that produces the tutorial handout:
%-*-latex-*-
\documentclass[m263,notes,10pt,fontsLuc,layoutNoMpar]{myModNotes04}
\NMsetDates{2007}
\NMdocDate{16 January 2008}
\NMbaseURL{\Htag{baseURL}}
\NMthisTopic{Units 7 \& 8 Tutorial}
\NMthisFile{tutorialU7U82007J}
\NMwrittenBy{Phil Molyneux (with Alex McGuiggan, Claudi Thomas, Tim Lister)}
\NMthisFileExt{.pdf}
\renewcommand{\familydefault}{\sfdefault}
\usepackage{ragged2e}
\input{treeEGs2006}
\begin{document}
\NMmakeTitle
\input{tutorialU7U82006agenda01}
\clearpage
\section*{Exercises}
\begin{enumerate}
\item \label{qSets}
\input{tutorialU7U82006qSets02}
\item \label{q01BinTrees}
\input{tutorialU7U82006q01BinTrees04}
\item \label{q02BinTrees}
\input{tutorialU7U82006q02BinTrees05}
(the rest of the file and input files are not shown)
Note the \label commands — they are used for cross-referencing
29
top related