90 likes | 174 Views
Explore the concepts of binary search trees (BST) presented by Neil Ghani from the University of Strathclyde. Learn the characteristics and examples of BSTs, along with algorithms for searching and checking BSTs.
E N D
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)
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
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
(Non) Examples of BSTs • 12 / \ 6 15 / \ 4 14 Is not a BST as condition 3 fails
(Non) Examples of BSTs • 12 / \ 9 15 / \ 4 8 Is not a BST as condition 1 fails
Examples of BSTs • 12 / \ 8 15 / \ 4 9 is a BST!
Checking BSTs • Here is an algorithm to check if a tree is a BST isBST (leaf x) = True isBST (node l x r) = isBST l && isBST r && max l <= x && min r >= x
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 False find x (node l y r) = if x == y then True else if x < y then find x l else find x r