0% found this document useful (0 votes)
32 views79 pages

Topic 5

Uploaded by

simon21tt
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)
32 views79 pages

Topic 5

Uploaded by

simon21tt
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

Topic 5

Abstract Data Structures

© Justin Robertson 2019. All rights reserved.


Array
▪ An array is a list data structure in which elements are of
the same type and stored in adjacent memory addresses .
▪ This fact leads to three key characteristics:
₋ Arrays support direct access because it is possible to
mathematically calculate the address of a particular
element, allowing you to jump straight to where it is.
₋ You have to declare how big your array should be
before you can use it. This can cause problems if you
don't know how many elements your program needs.
₋ It's difficult to insert values into the middle of an
array because elements need to be shifted along to
make room.

© Justin Robertson 2019. All rights reserved.


Array operations
NUMS

457 239 754 123 97 13 386 334

[0] [1] [2] [3] [4] [5] [6] [7]

Array elements are accessed using subscript notation:


NUMS[2]
// 754
They can be written to in the same way:
NUMS[4] = 98
// Changes the 97 to 98
Their structure lends itself to processing using loops:
loop J from 0 to 7
NUMS[J] = 0
end loop
// resets every element to zero
© Justin Robertson 2019. All rights reserved.
Two-dimensional arrays

Three different
representations of
the same 2d array

What numbers are referenced by the following?


(a) NUMS[0][0] (b) NUMS[1][3] (c) NUMS[2][1]

© Justin Robertson 2019. All rights reserved.


2d arrays and nested loops
loop I from 0 to 2
loop J from 0 to 3
output(ARRAY[I][J])
end loop
end loop

Note that IB pseudocode doesn't


give arrays a length property.

for (int i = 0; i < [Link]; i++) { Practice


for (int j = 0; j < array [i].length; j++) {
[Link](array[i][j]); Construct code that will
} output:
}
● The sum of all the
numbers
In Java, 2d arrays are in fact arrays of arrays. Note ● The sum of each row of
carefully that the inner for loop runs up to numbers
array[i].length, not [Link]. ● The sum of each column
of numbers

© Justin Robertson 2019. All rights reserved.


Linked List
HEAD

23 34 54 77 89

Linked lists are normally drawn with boxes and arrows but really they are more like
this...

3F4C
data: 54
next: 3348
HEAD: AF34
210E
data: 34 AF34
next: 3F4C data: 23
next: 210E 3348
124B
data: 77
data: 89
next: 124B
next: 0000

© Justin Robertson 2019. All rights reserved.


Linked list nodes
HEAD

23 34 54 77 89

Each element of a linked list is


called a node . At the least it has (a)
3F4C some way to store information and
data: 54
(b) a reference to the next node.
next: 3348 The code for a Node class in Java
HEAD: AF34 would be something like this:
3348
210E
class Node {
data: 77
data: 34
int data;
next: 124B
next: 3F4C
Node next;
AF34 }
124B
data: 23
data: 89
next: 210E
next: 0000

© Justin Robertson 2019. All rights reserved.


Constructing a linked list
HEAD

23 34 54 77 89

You could make this linked list using the Here is the code to add a node on the end
following code: of the list:
Node head = new Node(); Node newNode = new Node();
[Link] = 23; [Link] = 100;
[Link] = new Node(); if (head == null) {
[Link] = 34; head = newNode;
[Link] = new Node(); }
[Link] = 54; else {
[Link] = new Node(); Node tmp = head;
[Link] = 77; while ([Link] != null) {
[Link] = new Node(); tmp = [Link];
[Link] = 89; }
[Link] = newNode;
But as you can see, this approach is not }
workable as the list grows in size. Instead You no longer need to know how to code
we use loops to add nodes. linked list algorithms, but you may well
need to describe linked lists, how they are
constructed and how data is inserted.

© Justin Robertson 2019. All rights reserved.


Types of linked list
Singly linked list. This is
HEAD

4 12 32 44 79 the vanilla linked list.

Singly linked list with a tail pointer.


4 12 32 … 44 79 The tail pointer allows this list to
support queue operations more easily.

FRONT BACK

Doubly linked list. Each node has a


HEAD

4 12 32 44 "prev" as well as a next. This allows you


to access nodes in reverse order .

Circular linked list. There is no tail as


such because it just points round back
HEAD

4 12 32 44 79 to the head. This is good for modelling


any order that is inherently circular,
such as round-robin scheduling.
HEAD

4 12 32 44 Circular doubly linked list. You can


go round the circle in either direction!

© Justin Robertson 2019. All rights reserved.


Sketching linked list insertion
Step 1: 24 N = NEW NODE()

N
To insert a new node,
you need a pointer to the
node before the location

HEAD
where the new node will 4 12 32 44 79
go. Make sure you
understand why. Can you

TMP
explain why?

Step 2: 24 [Link] = [Link]

N
The next thing to do is
get the new node's next
pointer to point to the
HEAD

tmp's next pointer. 4 12 32 44 79


TMP

Step 3: 24
N

Finally TMP's next [Link] = N


pointer points to the new
node. Note that you
HEAD

cannot do step 3 before 4 12 32 44 79


you do step 2. Can you
explain why not?
TMP

© Justin Robertson 2019. All rights reserved.


Basic Linked List Operations Animation
Follow this link for a presentation showing animations of the basic linked list
operations.

Some of the animations assume you already have a tail pointer , or a pointer to the
last-but-one node.

If you don't already have those for your own linked list operations, it is easy to find the
end of the list using this code:

Node tmp = head;


while ([Link] != null) {
tmp = [Link];
}

And if you want to find the last-but-one node , you can do this:
Node tmp = head;
Node lastButOne;
while ([Link] != null) {
lastButOne = tmp;
tmp = [Link];
}

© Justin Robertson 2019. All rights reserved.


Arrays vs Linked Lists
Arrays Linked Lists

▪ Arrays support direct access , so retrieving a ▪ Linked lists only support sequential access ;
value from the middle of the array is O(1) -- they don't support direct access since you
ie it's very quick. 👍 only have a pointer to the head node. This
▪ Arrays are static . That means you have to say means to retrieve a value from the middle of
how many elements you want when you the list you have to start at the beginning and
declare the array, ie before you use it. This loop through the list. This is O(N). 👎
could be bad if you don't know how many ▪ Linked lists are dynamic , which means you
elements you're likely to want. don't need to say how big they're going to
▪ If you declare too many and don't use them, get. 👍
then you waste memory . 👎 ▪ Linked lists never waste memory because
▪ If you don't declare enough and you need they only contain nodes which have data in
more, then you have to create a whole new them. You also never run out of space to add
array and copy each element across. This nodes (unless I guess if you run out of
takes time . 👎 memory entirely). 👍
▪ Adding and deleting elements from the ▪ It is easy to insert into and delete from the
middle of an array is problematic as well, middle of a linked list.👍
because existing elements need to be shifted
along to make room , or shifted back in
order to fill up any holes created.👎

Click here to see an animation showing insertion into the middle of an array and a linked list.

© Justin Robertson 2019. All rights reserved.


Feynman Technique Activity: Arrays vs Linked Lists
Watch this short video on the Feynman Technique for Learning.
▪ Simple, uncluttered explanations of the main points
▪ Clear notes with plenty of diagrams
In pairs:
1. A explains to B the advantages and disadvantages of arrays .
2. B explains to A the advantages and disadvantages of linked
lists .
Work together for five minutes to plan one written page of notes.
It should contains definitions , explanations (fact + reason) and
plenty of simply annotated diagrams .
Once your plan is done, produce the page of notes and share a
good photo of it.
© Justin Robertson 2019. All rights reserved.
Linked List Activity
Prepare cards as follows (add extra as necessary Using these rules, practice the following algorithms:
depending on your number of students )
1. Finding a specific value in the list
Address: 6F31
Data: 34
Address: A112
Data: 45
Address: 3987
Data: 56
2. Finding the last node in the list
Next: A112 Next: 3987 Next: 100D

Mix students up so that they each get a turn at being


Address: 100D Address: 88C0 the head/tmp node.
Data: 73 Data: 82 Head: 6F31
Next: 88C0 Next: null Address:
Introduce further rules Data:

Shuffle all the cards, including the head pointer. Then (you will need two more students): Next:

give each student a card at random and tell them to keep


it secret. The head pointer should then identify herself 1. The head node can spontaneously create:
and write the address of the first node clearly on the a. A new node (use a blank card)
board. She will then play the part of a tmp pointer that b. A pointer pointing to that node
will traverse the list. 2. Any pointer pointing at a node can instruct
their node to change its data value and the
Rules: address it is pointing to.

1. Only the head/tmp pointer can ask questions. Using these rules, practice some of the algorithms on
2. Other students can only answer: the next slide.
a. Whose address is… [address]? (Student
answers by raising a hand.) Each time the group decides on an action, e.g.
b. The next two questions can only be asking/answering a question, changing a field value,
answered if the tmp pointer is pointing at the etc, get them to write it down on the board in
student: pseudocode. Build up the full pseudocode for each
i. What is the value of your data? algorithm.
ii. Where are you pointing?
© Justin Robertson 2019. All rights reserved.
returns true if the list is empty, otherwise false
Linked List Methods
isEmpty()

getFirstElement() returns the value of the head node

getLastElement() returns the value of the tail node On the left are some of the
insertAtHead(num) inserts num as the new head node methods you can include in
your linked list to make it
inserts num as the new tail node
more useful.
insertAtTail(num)

list() output every item in the list


Concept questions:
getCount() returns the number of elements in the list

exists(num) returns true if num is in the list Which methods are


getIndex(num) returns the (first) index of num in the list
necessary to use your list as
a stack? queue?
removeFromHead() removes the head node

removeFromTail() removes the tail node


The getNthElement and
setNthElement mimic the
removes (first, all, etc) occurrences of num from
removeElement(num)
the list type of direct access that an
array supports. Does this
getNthElement(n) returns the nth element from the list
mean your list supports
setNthElement(n, num) sets the data value of the nth element to num direct access? Discuss.
insertInOrder(num) inserts num in the right order (ascending or
descending as required) From the Guide:
Methods that should be known
Note that we have conceived of a class and specified its behaviour without implementing it in are add (head and tail), insert (in
any way. We could just as easily use an array to create this behaviour. This is the idea behind order), delete, list, isEmpty, isFull.
Abstract Data Types (ADTs) . ADTs like this are Collections .
© Justin Robertson 2019. All rights reserved.
public class LinkedListDemo {

Java Code Scaffold


public static void main(String[] args){
[Link](null);
// remove the call to [Link]() and add
// your own code to test the methods you have coded.
}
}

The code on the right can be given to students to class LinkedList {

scaffold a LinkedList coding task in Java.


Node head;

public static void main(String[] args){


// This is just a demo
In Netbeans students would need to name their LinkedList list = new LinkedList();

project LinkedListDemo and paste the code in to


int i = 1;
[Link] = new Node();
their main class window. Alternatively this can be [Link] = i;
Node p = [Link];
saved to [Link] and compiled from do {
i++;
the command line using javac. [Link] = new Node();
p = [Link];
[Link] = i;
After the Linked List activity, ask students to work } while (i < 10);
[Link]();
in small coding teams to code the methods in the }

LinkedList class. void print(){


Node p = head;
[Link]("HEAD->");
Notes: while (p != null){
[Link]([Link] + "->");
p = [Link];
insertInOrder() is quite challenging and is probably }
[Link]();
beyond the scope of the course. Students will have }

to think hard about all the possible preconditions void insertAtFront(int n) { // insert code }
such as the list is empty, the new node should be void insertAtTail(int n) { // insert code }
placed at the start, middle, end of the list.
void insertInOrder(int n) { // insert code }

boolean isEmpty(){ // insert code }


}

class Node {
int data;
Node next;
}

© Justin Robertson 2019. All rights reserved.


Stack
▪ A stack a special type of list in which you can
only add and remove items from one end.
▪ It's called a LIFO (last in first out) data
structure because the last item added will
always be the first one removed.
▪ It's called a stack because it's like a stack of
plates. You can only add and remove plates
from the top of the stack.
▪ Conventionally, the function to add an item
is called push and the function to remove an
item is called pop.
▪ The last function that you need to remember
is isEmpty , which should check to see if the
stack is empty and which is used to ensure
you don't try to pop from an empty stack.
© Justin Robertson 2019. All rights reserved.
Stack: Java code
▪ The syllabus requires that you can
construct code for the pop, push
and isEmpty methods.
▪ You may also be required to draw
a diagram of the stack before and
after various calls to push and pop.

▪ This stack uses an array to hold


integers.
▪ It has room for 100 integers but it
must maintain a stack pointer to
show where the top of the stack is.
▪ Remember that
₋ push takes an argument but
returns void
₋ pop doesn't take an argument
but returns a value

© Justin Robertson 2019. All rights reserved.


Uses of Stacks
Browser back button
Word processor undo button
The call stack
Evaluating expressions

© Justin Robertson 2019. All rights reserved.


Queue
▪ A queue a special type of list in which you can only add
items to one end and remove items from the other.
▪ It's called a FIFO (first in first out) data structure because
the first item added will always be the first one removed.
▪ It's called a queue because…
▪ Conventionally, the function to add an item is called
enqueue and the function to remove an item is called
dequeue .
▪ The last function that you need to remember is isEmpty ,
which should check to see if the queue is empty and which
is used to ensure you don't try to dequeue from an empty
queue.

© Justin Robertson 2019. All rights reserved.


Uses of Queues
Keyboard buffers
Print queues
CPU scheduling

© Justin Robertson 2019. All rights reserved.


Recursion

© Justin Robertson 2019. All rights reserved.


Towers of Hanoi

© Justin Robertson 2019. All rights reserved.


This is the Towers of Hanoi. You may have seen it before. You have
three rods, and some discs which have holes in and slide over the
rods.

1 2 3
You have to move all of the discs from 1 to 3 subject to two rules.

1 2 3
You can only move one disc at a time.

1 2 3
1 2 3
And you can't put a larger disc on top of a smaller one.

1 2 3
Now, you could start moving stuff about randomly, but you will
quickly find that this is actually quite a tough problem, especially if
you have more than a few discs. A moment's thought draws your
attention to this guy.

1 2 3
Think:
What will the state of the game be when you come to move this
disc? Take one full minute to think about it. Don't shout out. We
will discuss it in a moment.

1 2 3
Because this one is the biggest, when you move it, you will have to
move it to a rod that is empty, and if you want to move it from 1 to
3, then all the others need to be on 2. You quickly realise that at
some point, you will have to get to this next position...

1 2 3
Once you have reached this position, then you can move the big
one over...

1 2 3
And then work on getting the others from 2 to 3.

1 2 3
But how can you get the first four from 1 to 2? Let's consider this as
a separate problem.

1 2 3
A moment's thought draws your attention to this guy. Like before,
if you want to move it from 1 to 2, then all the others need to be on
3 and you quickly realise that at some point, you will have to get to
this position...

1 2 3
Then you can slide the big one over, etc.

1 2 3
The problem of the Towers of Hanoi is to move N
discs from the source peg to the destination peg via
the intermediate peg.

In order to solve this problem, we must first move


N-1 discs from the source peg to the intermediate peg
via the destination peg. Then we move the big disc
from the source to the destination peg. Then we again
move N-1, but this time from the intermediate peg to
the destination peg.

Take some time to consolidate your understanding of


this.
So the solution to the N disc Towers of Hanoi problem
can be given in terms of solutions to the N-1 disc Towers
of Hanoi problem, and the solution to the N-1 disc
Towers of Hanoi problem can be given in terms of
solutions to the N-2 disc Towers of Hanoi problem, and
so on until we get to the 1 disc Towers of Hanoi problem,
which is trivial.

When a problem can be solved in terms of the solutions


to smaller versions of the same problem it is said to have
a recursive solution.

The 1 disc problem is said to be the base case . It


represents the condition under which we stop recursing.
In computing, a recursive function is one which
includes in its body at least one call to itself. Here is a
Java function that prints the numbers from 1 to 10
using recursion.

What is the base


case here?

This example would reward some study if you haven't


seen recursion before. Take time to understand
exactly how it works. It highlights one disadvantage
of recursion: it can be quite confusing, especially
to new programmers.
The call stack for the printRecursivelyUpTo function
printRecursivelyUpTo(10)
printRecursivelyUpTo(9)
printRecursivelyUpTo(8)
printRecursivelyUpTo(7)
printRecursivelyUpTo(6)
printRecursivelyUpTo(5)
printRecursivelyUpTo(4)
printRecursivelyUpTo(3)
printRecursivelyUpTo(2)
printRecursivelyUpTo(1)
printRecursivelyUpTo(0)
return;
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
[Link](6);
[Link](7);
[Link](8);
[Link](9);
[Link](10);

© Justin Robertson 2019. All rights reserved.


In order to program a solution to the Towers of
Hanoi problem, we need to create a function which
we can call recursively.

So if we wanted to set up a Towers of Hanoi problem


of moving 7 discs from peg 1 to the peg 3 via peg 2
then you would use this call:

© Justin Robertson 2019. All rights reserved.


Now, the recursive solution to the Towers of Hanoi
problem was something like this:

move n-1 discs from the source to the intermediate


move the one big disc from the source to the destination
move n-1 discs from the intermediate to the destination

And the base case was:

if there is only one disc:


move the disc from the source to the destination

So if we write this in our Java function it would be:

© Justin Robertson 2019. All rights reserved.


We now just need to add our base case:

if there is only one disc:


move the disc from the source to the destination

And our function is now:

But that can't be it, right?

© Justin Robertson 2019. All rights reserved.


Code

Function Output
call
Actually it is.

Remarkably, although it may feel like we


have only really described how to solve the
problem, rather than actually solving it,
this code works.

The example given is for the 4 disc


problem.
© Justin Robertson 2019. All rights reserved.
Recursion recap

Make a copy of the worksheet and enter your


answers. Try on your own before you discuss with
your table.

▪ Define recursive function. [1 mark]


▪ State one advantage of recursion and one
disadvantage of recursion. [2 marks]
▪ Outline how recursion can be used in a binary
search. [3 marks]

Recursion worksheet
© Justin Robertson 2019. All rights reserved.
Discuss in your table
groups.
● In what ways is this
pattern recursive in
nature?

This is created using a


recursive function in
Scratch.
● What would the base case
be?
● What parameters do you
think the function must
take?
● What would the recursive
function call be?
● Write the function in
pseudocode.

© Justin Robertson 2019. All rights reserved.


© Justin Robertson 2019. All rights reserved.
This is a Sierpinski Triangle

See if you can write the


pseudocode

Hints:

● The biggest triangle is drawn


first.
● Each call to the Sierpinski
function draws one triangle
only.
● The Sierpinski function
contains three recursive calls.

© Justin Robertson 2019. All rights reserved.


Generalized recursive function
func (arg1, arg2, …) {

if (arg1 == base_case) {

return [value]

else {

[perform some task]

[value = ] func (arg1 (closer to base case), arg2, …)

[perform some task]

© Justin Robertson 2019. All rights reserved.


Binary Trees

© Justin Robertson 2019. All rights reserved.


Binary tree: A tree in which
Binary tree structure each node has at most two
children.
Tree: A non-linear data structure
Strictly binary tree: A tree
(representing a strictly hierarchical
in which each node has
system of data) where each data
precisely two children.
item is thought of as a node.
Node structure

A data field and two pointers, left and right

Data
All the nodes together form a
binary tree. The nodes within
Recursive! the red triangle also form a
binary tree. The nodes within
the blue triangle also form a
binary tree. How may binary
trees are there in total?
Binary search tree
50

25 76

12 37 65 89

6 17 32 41 59 72 83 95

Binary search tree: A binary tree that has the following properties:
• The left subtree of a node contains only nodes with data less than the node's data.
• The right subtree of a node contains only nodes with data greater than the node's data.
• Both the left and right subtrees are also binary search trees.
Terminology
Parent of the root node
node that
contains 12
Right subtree of
50
the tree of which
Left child of the the 76 node is
node that 25 76 the root
contains 25

12 37 65 89

6 17 32 41 59 72 83 95

Leaf nodes
Binary trees don’t have to be symmetrical
Insertion operation
We want to insert a new node into the tree. Where should we put it?

63

50

25 76

12 37 65 89

6 17 32 41 59 72 83 95
Insertion operation
It is bigger than 50, so go
down the right subtree…

50 63

25 76

12 37 65 89

6 17 32 41 59 72 83 95
Insertion operation
It is smaller than 76, so go
down the left subtree…

50

25 76
63

12 37 65 89

6 17 32 41 59 72 83 95
Insertion operation
It is smaller than 65, so go
down the left subtree…

50

25 76

12 37 65 89

63

6 17 32 41 59 72 83 95
Insertion operation
It is bigger than 59, and
59 has no right children,
so that’s where it goes.

50

25 76

12 37 65 89

6 17 32 41 59 72 83 95

63
Task
Think about how you would code the insert operation…

50

25 76

12 37 65 89

6 17 32 41 59 72 83 95

63
The iterative way
Don’t think about this too long because there is a beautifully elegant alternative…
private Node root;

public void insert(int data) {


if (root == null) {
root = new Node(data);
return;
}
Node tmp = root;
while (true) {
if (data == [Link]()) { // Data is already in the tree 50
return;
} else if (data < [Link]()) {
// insert left 25 76
if ([Link]() == null) {
[Link](new Node(data));
return;
} else {
tmp = [Link]();
12 37 65 89
}
} else {
// insert right
if ([Link]() == null) {
[Link](new Node(data));
return; 6 17 32 41 59 72 83 95
} else {
tmp = [Link]();
} 63
}
}
}
The recursive way
Recursion is sometimes tough to get your head round. But can be very simple and very elegant.

void insertNode(Node root, int data)


{
if (data < [Link]()){
if([Link]() == null){
[Link](new Node(data));
}
else { 50
insertNode([Link](), data);
}
} 25 76
else {
if([Link]() == null){
[Link](new Node(data));
} 12 37 65 89
else {
insertNode([Link](), data);
}
}
} 6 17 32 41 59 72 83 95

You could be expected to be able 63


to code this type of method from
scratch for your exam
Binary Tree Traversals
"Traversing" a binary tree
means visiting every node
in turn.

There are three types of


traversal:
• Preorder 50
• Inorder
• Postorder
25 76

12 37 65 89

6 17 32 41 59 72 83 95
Binary Tree Traversals
Let's say that you want to print out your binary tree. Here are the three different
traversals.

Preorder: Inorder: Postorder:


When you get to a node: When you get to a node: When you get to a node:
Print the node's data. Traverse its left subtree. Traverse its left subtree.
Then traverse its left subtree. Then print the node's data. Then traverse its right subtree.
Then traverse its right subtree. Then traverse its right subtree. Then print the node's data.

void preOrder(Node n){ void inOrder(Node n){ void postOrder(Node n){


if(n == null) return; if(n == null) return; if(n == null) return;
print(n); inOrder([Link]); postOrder([Link]);
preOrder([Link]); print(n); postOrder([Link]);
preOrder([Link]); inOrder([Link]); print(n);
} } }

Which of these would you want to use to print your binary search tree in ascending order?
Task
Write down the order of the numbers as printed by each of the traversals.
void preOrder(Node n){
if(n == null) return;
print(n);
preOrder([Link]); 50
preOrder([Link]);
}
25 76
void inOrder(Node n){
if(n == null) return;
inOrder([Link]);
print(n);
89
inOrder([Link]);
} 12 37 65

void postOrder(Node n){


if(n == null) return;
postOrder([Link]);
postOrder([Link]);
print(n);
6 17 32 41 59 72 83 95
}
This is not on the syllabus any more but it's a good example of how binary trees are used.

Infix, prefix and postfix notation


Consider the following mathematical expression:

4 × (3 + 8)
This is written in what is called infix notation, in which the operators (+, - , x, /) are
written between their operands. It is the usual notation that you are familiar with
from mathematics.

However, there are two other ways of writing expressions like these, and both of
them are used in computer science.

In prefix notation, also known as Polish notation, the operators come before their
operands.

In postfix notation, also known as Reverse Polish notation, the operators come
after their operands.

(All operators are assumed to be binary.)


This is not on the syllabus any more but it's a good example of how binary trees are used.

Examples
Infix: 4 × (3 + 8)
Prefix: × 4 + 3 8
Postfix: 4 3 8 + ×

Convert the following expressions to prefix and postfix:

1. 4+5
2. 4/3+7
3. (5 + 2) × (3 + 1)
4. 4 / (3 + 6) + 5 × 9
This is not on the syllabus any more but it's a good example of how binary trees are used.

Why use different notations?


Computers normally convert all infix expressions to
postfix.

Reasons:

• Brackets are not necessary in postfix expressions


• There are no rules about precedence in postfix
expressions, as there are in infix expressions
• Postfix expressions are easy to evaluate using
stacks
• Stacks are fast and easy to program
This is not on the syllabus any more but it's a good example of how binary trees are used.

What has this got to do with binary trees?

What happens when the following tree is printed:


• preorder?
• inorder?
• postorder?
This is not on the syllabus any more but it's a good example of how binary trees are used.

Using stacks to evaluate postfix expressions

• When we see an operand, push it onto the stack


• When we see an operator, pop two operands
from the stack, do the operation, and push the
answer onto the stack
• Loop

If you follow this algorithm, you will be left with one


value on the stack, which is the answer to the
expression.
This is not on the syllabus any more but it's a good example of how binary trees are used.

Task
• Create annotated notes in Word, using drawing
objects.
• Show how 5 x (4 + 3) is converted to postfix
notation.
• Show how the postfix expression is evaluated
using a stack.
This is not on the syllabus any more but it's a good example of how binary trees are used.

Task answer
Parse expression 5 × (4 + 3)
1
3
Convert to postfix: 543+×
Push 5 4

Push 4
5
Push 3 (diagram 1)

Pop 3 2
7
Pop 4
5
Push 3 + 4 = 7 (diagram 2)
Pop 7
3
Pop 5 35

Push 7 × 5 = 35 (diagram 3)
Past exam questions
Past exam questions (cont.)
Recursion Advantages:
● Some problems are much easier to
A recursive function is a function that calls itself, either
program using recursion.
directly or indirectly. Recursion is a powerful programming
technique in which a problem is divided into a set of similar
subproblems, each solved with a trivial solution. Generally, a Disadvantages:
recursive function calls itself to solve its subproblems. ● Can be confusing.
Douglas Crockford, JavaScript the Good Parts, 2008 ● Can take up a lot of memory with
repeated calls.
● Can be slower than iterative
int fib(int n) { alternatives.
if (n <= 1)
return n;
else
return (fib(n-1) + fib(n-2));
}
boolean binSearch(int[] x, int start, int end, int n)
{
int gcd(int m, int n) { if (end < start) return false;
if ((m % n) == 0) int mid = (start+end) / 2;
return n; if (x[mid] == n) {
return true;
else } else {
return gcd(n, m % n); if (x[mid] < n) {
} return binSearch(x, mid+1, end, n);
} else {
return binSearch(x, start, mid-1, n);
int factorial(int n) { }
if (n == 0) }
return 1; }
else
return (n * factorial(n-1));
} © Justin Robertson 2019. All rights reserved.
Junk

32 8 21 10
[0] [0] [1] [2] [3]

[1]
4 64 24 19
[2] [0] [1] [2] [3]

44 13 73 50
[0] [1] [2] [3]

[0] [1] [2] [3]

[0]
32 8 21 10
[1]
4 64 24 19
[2]
44 13 73 50

© Justin Robertson 2019. All rights reserved.


31

12 65

3 17 43 77

13 24 69

© Justin Robertson 2019. All rights reserved.

You might also like