lecture – searching a tree neil ghani university of strathclyde

9
Lecture – Searching a Tree Neil Ghani University of Strathclyde

Upload: emil-lester

Post on 04-Jan-2016

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture – Searching a Tree Neil Ghani University of Strathclyde

Lecture – Searching a Tree

Neil GhaniUniversity of Strathclyde

Page 2: Lecture – 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)

Page 3: Lecture – Searching a Tree Neil Ghani University of Strathclyde

Searching …

We can search a list in * Linear time under no assumptions * Logarithmic time if the list is sorted• We can search a tree in linear time * Preorder, inorder and postorder traversal• Can we search a tree in log-time if it is sorted

Page 4: Lecture – Searching a Tree Neil Ghani University of Strathclyde

What is a Binary Search Tree (BST)

• A leaf is always a BST

• A tree is a binary search tree (BST) iff * The left subtree is a BSTs * The right subtree is a BST * Left subtree data are less than the node * Right subtree data are more than the node

Page 5: Lecture – Searching a Tree Neil Ghani University of Strathclyde

(Non) Examples of BSTs

• 12 / \ 6 15 / \ 4 14

Is not a BST as condition 3 fails

Page 6: Lecture – Searching a Tree Neil Ghani University of Strathclyde

(Non) Examples of BSTs

• 12 / \ 9 15 / \ 4 8

Is not a BST as condition 1 fails

Page 7: Lecture – Searching a Tree Neil Ghani University of Strathclyde

Examples of BSTs

• 12 / \ 8 15 / \ 4 9

is a BST!

Page 8: Lecture – Searching a Tree Neil Ghani University of Strathclyde

Checking BSTs

• Here is an algorithm to check if a tree is a BST

isBST (leaf x) = TrueisBST (node l x r) = isBST l && isBST r && max l <= x && min r >= x

Page 9: Lecture – Searching a Tree Neil Ghani University of Strathclyde

Searching a Binary Search Tree

• Algorithm: To find an element x in a BST t

find x (leaf y) = if x == y then True else Falsefind x (node l y r) = if x == y then True else if x < y then find x l else find x r