1 / 9

Lecture – Searching a Tree

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

lena
Download Presentation

Lecture – Searching a Tree

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 – 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

More Related