1 / 8

Lecture 6: An Introduction to Trees

Lecture 6: An Introduction to Trees. Neil Ghani University of Strathclyde. 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

annona
Télécharger la présentation

Lecture 6: An Introduction to Trees

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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

More Related