CS112 Fundamentals of
Programming Abstractions
Trees
Yinglin Wang
Dept, SJTU
CS112 Fundamentals of
Programming Abstractions
contents
Review of listADT
Trees
Binary trees
Binary search trees

This
** preview**
has intentionally

**sections.**

*blurred***to view the full version.**

*Sign up*
CS112 Fundamentals of
Programming Abstractions
Review of Using listADT: An
Exercise
How would we write a recursive
function to sort a list? There are two
things that suggest that we might
want to consider the first element in
relation to the rest of the list.
First, our general approach to
recursion involves reducing the
problem to a simpler one of the same
form. For lists, the easiest way to
come up with a simpler list is to look
at the tail.
Second, the recursive design of the
data structure draws our attention to
the tail of the list. What else is there
to do recursion on?
Sorting a list
(7 2 9 6 3 8)
7 (2 9 6 3 8)
CS112 Fundamentals of
Programming Abstractions
The Belief
What would the recursion
on the tail accomplish? It
would sort it.
Sorting a list
(7 2 9 6 3 8)
7 (2 3 6 8 9)

CS112 Fundamentals of
Programming Abstractions
Combine the Result of Simpler
Problems
Now if we could just
insert the first element of
the original list into the
proper place in the sorted
tail, it would be done.
Sorting a list
(7 2 9 6 3 8)
(2 3 6 7 8 9)
CS112 Fundamentals of
Programming Abstractions
The Codes
The main function is
really simple.This is
one of those cases
where recursion
almost seems like
cheating.
This definition says:
"to sort a list, just
insert the first
element into the
sorted tail." Easy!
listADT ListSort(listADT list)
{
if (list == NULL) return NULL;
return ListInsert(ListHead(list),
ListSort(ListTail(list)));
}

This
** preview**
has intentionally

**sections.**

*blurred***to view the full version.**

*Sign up*