CS241: Spring 2015 -- Lecture 20, Binary trees, Binary search trees, & tree sort!
Administrivia
Exam 3/13!
Review sheet up
Jury duty for me 3/12
Next week is review
Hard deadline for Monday lab (so you can have time to study/review)
Running times: why Θ is better than O! And why it's not entirely simple.
Best case
Worst case
Average case
Finishing up fib(1000) -- a homemade BigInt class (Java has BigInteger, but it's not difficult to write your own; often a
choice -- learn to use a built in class, or write your own)
arbitrarly big ints (well, at least until we run out of memory!)
representation: list of digits. Biggest first? Smallest first?
operations:
new
add(BigInt)
toString
Testing before use!!
Tired of linear strutures? Time for a recursive structure. Namely, Binary Tree
Metaphors (mixed): family tree, vegetable
Terminology (even more mixed): root, leaf, sibling, parent, child, subtree, ancestor, descendant, interior node, level, depth (of a node),
height (of a tree), traversal
Formal Recursive Definition (suitable for memorization) - a binary tree is either empty,
or it has a root and two subtrees, right and left (each is a binary tree).
According to this definition every leaf has two empty subtrees!
Be aware of the difference between formal use of the definition and casual description -- the latter is used for talking/thinking about binary trees,
the former for writing code.
A binary search tree (BST) is a binary tree with the property that every
node in the left subtree is less than the root and every node in the right
subtree is greater than or equal to the root. Every subtree in a BST has
this property as well (recursively!).
BST insert pseudocode
void insert(Integer insertMe) {
if (isEmpty()) // base case
setRoot(insertMe);
else if (belongsOnTheRight(insertMe))
right.insert(insertMe);
else left.insert(insertMe);
}
Tree sort - given an unsorted list
insert each element in a BST
empty the list
traverse the BST inorder, emit the root of each non-empty BST to the list