Binary Search Trees (BST) Let’s look at some pics …and some code.
BST A binary tree with data arranged such that data in each node >= data in its left child node AND < the data in its right child node Why use them? – one can search, insert, delete items quickly, vs. linked lists
Pictoral Representation
Building a BST Similar to the way sorted linked list was built!
Adding a node Drawing a picture is always a good idea!
Adding a node public class BinarySearchTree { private Node root; public void insert(int value){ Node node = new Node<>(value); if ( root == null ) { root = node; return; } insertRec(root, node); } private void insertRec(Node latestRoot, Node node){ if ( latestRoot.value > node.value){ if ( latestRoot.left == null ){ latestRoot.left = node; return; } else{ insertRec(latestRoot.left, node); } } else{ if (latestRoot.right == null){ latestRoot.right = node; return; } else{ insertRec(latestRoot.right, node); } } } }
Finding the min… What is the big-O order ?
Finding the max… What is the big-O order ?
Source code… public int findMinimum(){ if ( root == null ){ return 0; } Node currNode = root; while(currNode.left != null){ currNode = currNode.left; } return currNode.value; }
Let’s tiptoe through the BST Three ways to traverse the tree: – Inorder Traversal – Preorder Traversal – Postorder Traversal Each public method: calls a private recursive helper method (similar to what we did for add() in the sorted linked list)
Inorder Traversal
What is the result here?
Code for InOrder Traversal public void printInorder() { printInOrder(root); System.out.println(""); } private void printInOrder(Node currentRoot) { if ( currentRoot == null ){ return; } printInOrder(currentRoot.left); System.out.print(currentRoot.data + ", "); printInOrder(currentRoot.right); }
Preorder Traversal Pictorally:
Preorder Traversal public void printPreorder() { printPreOrder(root); System.out.println(""); } private void printPreOrder(Node currentRoot) { if (currentRoot == null) { return; } System.out.print(currentRoot.data + ", "); printPreOrder(currentRoot.left); printPreOrder(currentRoot.right); }
Postorder Traversal Pictorally:
PostOrder Traversal public void printPostorder() { printPostOrderRec(root); System.out.println(""); } private void printPostOrder (Node currentRoot) { if (currentRoot == null) { return; } printPostOrder (currentRoot.left); printPostOrder (currentRoot.right); System.out.print(currentRoot.data + ", "); }