Tuesday, 11 March 2014

Linked Structures

The central topic of Week 8 has been linked lists and a variant of binary trees - binary search trees (BSTs). Both these data structures are related by one particular property: each node (or element) of these data structures contains a reference to one (in the case of linked lists) or more (two in the case of BSTs) 'child' node(s).

For linked lists, we considered two definitions:

1. Lists containing an item (head) and the remaining linked list (rest).

2. As individual objects (nodes) containing some value and a reference to another node.

Though we saw in class that both these definitions employ similar functions - some functions are implemented quite differently, however the general structure/usage of linked lists stays the same.

Speaking of linked list usage, one interesting point mentioned in lecture this week was different usages of prepend(head).

In past weeks you would make a copy of the linked list and assign this copy as 'rest'. Then 'head' would become the new head being prepended. However, an alternative implementation was to make a new linked list in the prepend function where 'head' is the new head and 'rest' is self. Then this new linked list was returned. This seems a lot cleaner but requires the client to update their linked list every time prepend it called. I.e. x.prepend(1) becomes x = x.prepend(1).

Besides linked lists we looked at BSTs, a variant of binary trees already seen in past weeks. We looked at BSTs of the following kind: binary trees with the constraint that the left child is smaller than the root and the right child is larger than the root.

It was claimed that this would allow for more efficient searches. At first I didn't see how this claim was true, but thinking recursively I realized that when we say the left child is always smaller than the root, the entire left subtree will contain elements smaller than root and vice versa for the right child/subtree.

This all relies on the recursive insert(item) function that ensures that the constraint holds. Observing the way insert worked really helped solidify my understanding of recursion in binary trees and now we have a neat O(log n) search algorithm to make use of!




No comments:

Post a Comment