Download presentation
Presentation is loading. Please wait.
Published byEmil Lester Modified over 9 years ago
1
Lecture – Searching a Tree Neil Ghani University of Strathclyde
2
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)
3
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
4
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
5
(Non) Examples of BSTs 12 / \ 6 15 / \ 4 14 Is not a BST as condition 3 fails
6
(Non) Examples of BSTs 12 / \ 9 15 / \ 4 8 Is not a BST as condition 1 fails
7
Examples of BSTs 12 / \ 8 15 / \ 4 9 is a BST!
8
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
9
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.