100 likes | 194 Views
Lecture 7: Searching a Tree. Neil Ghani University of Strathclyde. Recall. A Tree is either i) A leaf storing an integer ii) A node storing a left subtree, and integer and a right subtree For example, the following are trees leaf 5
E N D
Lecture 7: Searching a Tree Neil Ghani University of Strathclyde
Recall • A Tree is either i) A leaf storing an integer ii) A node storing a left subtree, and integer and a right subtree • For example, the following are trees leaf 5 node (leaf 5) 6 (leaf 4)
Defining Algorithms on Trees • We define algorithms on trees by saying i) What do they do on leaves ii) What do they do on nodes • For example, the reflect example ref (leaf x) = leaf x ref (node l x r) = node (ref r) x (ref l)
Examples • Example: An algorithm to add all the numbers in a tree sum (leaf x) = x sum (node l x r) = sum l + x + sum r Note the use of recursion. ALWAYS consider recursion • Example: Write an algorithm that takes a number and a tree as input and cuts the tree at that depth
Examples • Example: An algorithm that takes a number and a tree as input and cuts the tree at that depth cutAt 0 (leaf x) = leaf x cutAt 0 (node l x r) = leaf x cutAt (n+1) (node l x r) = node (cutAt n l) x (cutAt n r)
Searching Trees • We saw two algortihms for searching a list * Linear search which has O(n) complexity * Binary search which has O(log n) complxity • For trees, there are three linear algorithms * In-order search * Pre-order search * Post-order search
Pre-Order Traversal • Pre-order traversal looks at the root FIRST * Search the root * Search the left subtree * Search the right subtree • Example: Printing using preorder traversal pre (leaf x) = putStr x pre (node l x r) = putStr x; pre l; pre r
In-Order Traversal • In order traversal looks at the root second * Search the left subtree * Search the root * Search the right subtree • Example: Printing using inorder traversal inord (leaf x) = putStr x inord (node l x r) = inord l; putStr x; pre r
Post-Order Traversal • Post order traversal looks at the root LAST * Search the left subtree * Search the right subtree * Search the root • Example: Printing using postorder traversal post (leaf x) = putStr x post (node l x r) = post l; post r; putStr x;
Example • Traversing the following tree gives 6 / \ 3 5 / \ 4 8 pre:6, 3, 4, 8, 5 in:4, 3, 8, 6, 5 post:4, 8, 3, 5, 6