Dale - Computer Science Illuminated 332

Dale - Computer Science Illuminated 332 - current points to...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
9.7 Trees 305 Now let’s look at what happens when we search for a value that is not in the tree. Let’s look for 4. We compare 4 with 15. 4 is less than 15, so if 4 is in the tree it will be in the left subtree of the root. We compare 4 with 7, the value in the root of the left subtree. 4 is less than 7, so if 4 is in the tree it will be in 7’s left subtree. We compare 4 with 5. 4 is less than 5, so if 4 is in the tree it will be in 5’s left subtree. We compare 4 with 1. 4 is greater than 1, so if 4 is in the tree it will be in 1’s right subtree. But 1’s left subtree is empty, so we know that 4 is not in the tree. In a linked list the node contained an info part that contained the user’s data and a pointer to the next node in the list. If we are to implement a binary tree, the node must have three parts: the user’s data and a pointer to the left subtree and a pointer to the right subtree. If
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: current points to a node, info(current) refers to the users data in the node, left(current) points to the root of the left subtree of current , and right(current) points to the root of the right subtree of current . If a pointer contains null , the subtree is empty. Using this notation, we can now write the search algorithm. We start at the root of the tree and move to the root of successive subtrees until we find the item we are looking for or we find an empty subtree. The item to be searched for and the root of the tree (subtree) are parameters. Boolean IsThere(current, item) If (current is null) return false Else Set result to item.compareTo(info(current)) If (result is equal to 0) return true Else If (result < 0) IsThere(left(current, item)) Else IsThere(right(current, item) Pointer to the root of the left subtree Pointer to the root of the right subtree User's data...
View Full Document

Ask a homework question - tutors are online