Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 6: An Introduction to Trees Neil Ghani University of Strathclyde.

Similar presentations


Presentation on theme: "Lecture 6: An Introduction to Trees Neil Ghani University of Strathclyde."— Presentation transcript:

1 Lecture 6: An Introduction to Trees Neil Ghani University of Strathclyde

2 2. Recall We study the definition of algorithms - What do they do - Searching lists, sorting lists We study the complexity of algorithms - Worst case asymptotic complexity - Big-O notation - O(log n), O(n), O(n logn), O(n*n)

3 3. Algorithms You Should Know Searching Lists: - Linear Search, Logarithmic Search Sorting Lists: - Insertion Sort, Quicksort, Mergesort How many recursive calls, on what size input, and what other work is required

4 4. Trees What are trees? - Lists are linear data structures - Trees are branching data structures We picture trees as follows 6 / \ 5 2 / \ 1 8

5 5. Defining algorithms on Trees Constructors: Every tree is either i) a leaf storing an integer ii) a node storing an integer, a left subtree and a right subtree We define algorithms by defining i) what they do to a leaf ii) what they do to a node We almost always use recursion

6 6. Example Algorithms Example 1: Add 6 to all data in a tree add6 (leaf x) = leaf (x+6) add6 (node l x r) = node (add6 l) (x+6) (add6 r) Example 2: Reflect a tree ref (leaf x) = leaf x ref (node l x r) = node (ref l) x (ref r)

7 7. Some for you … Example: Write an algorithm which adds up all the numbers in a tree Example: Searching a tree for a piece of data find x (leaf y) = (x == y) find x (node l y r ) = (x == y) or find x l or find x r

8 8. Tougher examples Example: Write an algorithm that takes a sequence of directions and a tree as input, and returns the data stored at that location findAt [] (leaf x) = x findAt [] (nodel l x r) = x findAt (LEFT:ds) (node l x r) = findAt ds l findAt (RIGHT:ds) (node l x r) = findAt ds r


Download ppt "Lecture 6: An Introduction to Trees Neil Ghani University of Strathclyde."

Similar presentations


Ads by Google