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

Topic 5-Abstract Data Structures

IBDP CS HL Abstract DS

Uploaded by

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

Topic 5-Abstract Data Structures

IBDP CS HL Abstract DS

Uploaded by

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

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
NUM
S
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
representatio
ns 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 < array.length; i++) { Practice
for (int j = 0; j < array[i].length; j++) {
System.out.println(array[i][j]); Construct code that will
} output:
} ● The sum of all the
numbers
In Java, 2d arrays are in fact arrays of arrays. ● The sum of each
Note carefully that the inner for loop runs up to row of numbers
● The sum of each
array[i].length, not array.length.
column of numbers

© Justin Robertson 2019. All rights reserved.


Linked List
HEA

23 34 54 77 89
D

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
HEA

23 34 54 77 89
D

Each element of a linked list


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

© Justin Robertson 2019. All rights reserved.


Constructing a linked list
HEA

23 34 54 77 89
D

You could make this linked list using Here is the code to add a node on
the following code: the end of the list:
Node head = new Node(); Node newNode = new Node();
head.data = 23; newNode.data = 100;
head.next = new Node(); if (head == null) {
head.next.data = 34; head = newNode;
head.next.next = new Node(); }
head.next.next.data = 54; else {
head.next.next.next = new Node(); Node tmp = head;
head.next.next.next.data = 77; while (tmp.next != null) {
head.next.next.next.next = new Node(); tmp = tmp.next;
head.next.next.next.next.data = 89; }
tmp.next = newNode;
But as you can see, this approach is }
not workable as the list grows in You no longer need to know how to
size. Instead we use loops to add code linked list algorithms, but you
nodes. 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.
4 12 32 44 79
HEAD

This is the vanilla


linked list.

Singly linked list with a tail


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

FRONT BACK

Doubly linked list. Each node


HEAD

4 12 32 44 has a "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
HEAD

4 12 32 44 79 points round back 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
4 12 32 44 79

HEAD
before the location
where the new node
will go. Make sure

TMP
you understand why.
Can you explain
why?
Step 2: 24 N.NEXT = TMP.NEXT

N
The next thing to do
is get the new
node's next pointer
4 12 32 44 79
HEAD

to point to the tmp's


next pointer.
TMP

Step 3: 24
N

Finally TMP's next TMP.NEXT = N


pointer points to the
new node. Note that
4 12 32 44 79
HEAD

you cannot do step 3


before you do step
2. Can you explain
TMP

why not?

© 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 (tmp.next != null) {
tmp = tmp.next;
}

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

© Justin Robertson 2019. All rights reserved.


Arrays vs Linked Lists
Arrays Linked Lists

▪ Arrays support direct access, so ▪ Linked lists only support sequential


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

© 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. © Justin Robertson 2019. All rights reserved.
Linked List Activity
Prepare cards as follows (add extra as Using these rules, practice the following
necessary depending on your number of algorithms:
students )
Address: 6F31 Address: A112 Address: 3987 1. Finding a specific value in the list
Data: 34 Data: 45 Data: 56
Next: A112 Next: 3987 Next: 100D 2. Finding the last node in the list

Address: 100D Address: 88C0


Mix students up so that they each get a turn
Data: 73 Data: 82 Head: 6F31 at being the head/tmp node.
Next: 88C0 Next: null
Address:
Data:
Introduce further rules Next:

Shuffle all the cards, including the head pointer. (you will need two more students):
Then give each student a card at random and
tell them to keep it secret. The head pointer 3. The head node can spontaneously
should then identify herself and write the create:
address of the first node clearly on the board. a. A new node (use a blank card)
She will then play the part of a tmp pointer that b. A pointer pointing to that node
will traverse the list. 4. Any pointer pointing at a node can
instruct their node to change its data
Rules: value and the address it is pointing to.

1. Only the head/tmp pointer can ask Using these rules, practice some of the
questions. algorithms on the next slide.
2. Other students can only answer:
a. Whose address is… [address]? Each time the group decides on an action,
(Student answers by raising a hand.) e.g. asking/answering a question, changing
b. The next two questions can only be a field value, etc, get them to write it down
answered if the tmp pointer is on the board in pseudocode. Build up the
pointing at the student: full pseudocode for each algorithm.
© Justin Robertson 2019. All rights reserved.
isEmpty() returns true if the list is empty, otherwise false Linked List
getFirstElement() returns the value of the head node Methods
getLastElement() returns the value of the tail node On the left are some of
insertAtHead(num) inserts num as the new head node
the methods you can
include in your linked
insertAtTail(num) inserts num as the new tail node
list to make it more
list() output every item in the list useful.
getCount() returns the number of elements in the list
Concept questions:
exists(num) returns true if num is in the list

getIndex(num) returns the (first) index of num in the list


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

Java Code Scaffold


public static void main(String[] args){
LinkedList.main(null);
// remove the call to LinkedList.main() and add
// your own code to test the methods you have coded.
}
}
The code on the right can be given to class LinkedList {
students to scaffold a LinkedList coding Node head;

task in Java. public static void main(String[] args){


// This is just a demo
LinkedList list = new LinkedList();
In Netbeans students would need to name int i = 1;
list.head = new Node();
their project LinkedListDemo and paste the list.head.data = i;
Node p = list.head;
code in to their main class window. do {
i++;
Alternatively this can be saved to p.next = new Node();
LinkedListDemo.java and compiled from p = p.next;
p.data = i;
the command line using javac. } while (i < 10);
list.print();
}
After the Linked List activity, ask students void print(){
to work in small coding teams to code the Node p = head;
System.out.print("HEAD->");
methods in the LinkedList class. while (p != null){
System.out.print(p.data + "->");
p = p.next;
Notes: }
System.out.println();
}

insertInOrder() is quite challenging and is void insertAtFront(int n) { // insert code }

probably beyond the scope of the course. void insertAtTail(int n) { // insert code }
Students will have to think hard about all void insertInOrder(int n) { // insert code }
the possible preconditions such as the list
boolean isEmpty(){ // insert code }
is empty, the new node should be placed }

at the start, middle, end of the list. 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 © 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.


Recursio
n

© 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;
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
System.out.println(6);
System.out.println(7);
System.out.println(8);
System.out.println(9);
System.out.println(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 workshee
t © 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
Binary tree structure which each node has
at most two children.
Tree: A non-linear data
Strictly binary tree:
structure (representing a
A tree in which each
strictly hierarchical system of
node has precisely two
data) where each data item is
children.
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
Recursive! nodes within 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
50
of the tree of
Left child of which the 76
the node that 25 76 node is the
contains 25 root

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 == tmp.getData()) { // Data is already in the tree 50
return;
} else if (data < tmp.getData()) {
// insert left 25 76
if (tmp.getLeft() == null) {
tmp.setLeft(new Node(data));
return;
} else {
tmp = tmp.getLeft(); 89
12 37 65
}
} else {
// insert right
if (tmp.getRight() == null) {
tmp.setRight(new Node(data));
return; 6 17 32 41 59 72 83 95
} else {
tmp = tmp.getRight();
} 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 < root.getData()){
if(root.getLeft() == null){
root.setLeft(new Node(data));
}
else { 50
insertNode(root.getLeft(), data);
}
} 25 76
else {
if(root.getRight() == null){
root.setRight(new Node(data));
} 12 37 65 89
else {
insertNode(root.getRight(), data);
}
}
} 6 17 32 41 59 72 83 95
You could be expected to
be able to code this type of 63

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 Then print the node's Then traverse its right
subtree. data. subtree.
Then traverse its right Then traverse its right Then print the node's
subtree. subtree. 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(n.left); postOrder(n.left);
preOrder(n.left); print(n);
postOrder(n.right);
preOrder(n.right); inOrder(n.right); 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);
50
preOrder(n.left);

preOrder(n.right);
}
25 76
void inOrder(Node n){
if(n == null) return;

inOrder(n.left);
print(n);
12 37 65 89
inOrder(n.right);
}
void postOrder(Node n){
if(n == null) return;

postOrder(n.left); 6 17 32 41 59 72 83 95
postOrder(n.right);
print(n);
}
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
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?
Using stacks to evaluate postfix
This is not on the syllabus any more but it's a good example of how binary trees are used.

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
1
+ 3) 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.)
Recursio
n
Advantages:
A recursive function is a function that calls itself, ● Some problems are much easier to
either directly or indirectly. Recursion is a powerful program using recursion.
programming technique in which a problem is
divided into a set of similar subproblems, each Disadvantages:
solved with a trivial solution. Generally, a recursive ● Can be confusing.
function calls itself to solve its subproblems.
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) {
if (n <= 1) alternatives.
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