Binary Search Trees A binary tree is like a linked list, but instead of a single “next” link, it has two “left and right”. Everything smaller than, or equal to data gets assigned to left and everything greater than data gets assigned to right. Consider adding the numbers: 50,30,75,15,26,64,55,70 to a binary tree. It would end up looking like this: 50 30 75 15 64 26 55 70 With a simple binary search tree the efficiency of retrieving a given item depends heavily on the order the items were inserted. If a tree remains balanced searches would run at O(Log n). For now, all you need to know is: A balanced tree is faster Only as many comparisons as the tree has levels, and there will be O(Log n) levels Traversing a Tree The binary tree is a natural fit for recursive logic – since each node is a subset structure of the larger tree. Consider a print algorithm: PrintTree( node ){ if current.left !=null PrintTree( current.left ) Print Current if current.right !=null PrintTree(current.right) } This algorithm will print the list in order since it traverses down the left while left !=null. When left is null it prints the element (15), then Print the right node. Both elements are null there, so it just prints current. The previous recursive call continues and outputs current (30) then (50) and then moves on to print the right side of the tree. A search algorithm therefore would be: SearchTree( node, target){ If target=node Return node Else if target<=node and node.left!=null SearchTree( node.left, target) Else if target>node and node.right!=null SearchTree( node.right, target) Else Handle node not found exception } In this example we check to see if we are looking at the target node. If we are, we return it, if we’re not we follow the rules of the tree to find it: Search the left subtree if target is less than, or equal to current, and the right sub-tree if target is greater than current. Finally, let’s look at an add algorithm: AddNode(current, Integer temp){ If start=null Start=temp Else If current >= temp If current.left=null Current.left = new Node(temp) Else AddNode(current.left, temp) Else If current < temp If current.right=null Current.right = new Node(temp) Else AddNode(current.right, temp) This follows similar logic to the search algorithm. Navigate current to the correct end node (through sub-trees until there are no more sub-trees) and add temp to the correct pointer. Exercise Show a binary tree after these numbers are added: 8,5,7,6,3,8,9,2,1,0,2 Exercise Implement a Binary Tree of type Comparable which has the methods described above. Use it to store a dozen Widgets.