100 likes | 109 Views
CS 240: Data Structures. Monday, July 30 th Binary Search Trees. What are binary search trees?. Binary search trees are a data structure where each node has two links – compared to linked list which has 1. Generally, the links are called left and right. Node<T> *left; Node<T> *right;
E N D
CS 240: Data Structures Monday, July 30th Binary Search Trees
What are binary search trees? • Binary search trees are a data structure where each node has two links – compared to linked list which has 1. • Generally, the links are called left and right. • Node<T> *left; • Node<T> *right; • These, alternatively, could be stored in a list/vector of type “Node<T> *” contained in each node
Rules of the BST • A binary search tree has rules that govern how insertion works. • Smaller data goes on the left, larger/equal data goes on the right. • We will refer to the first node as root.
Initialize Tree Insert 5 NULL 5 Root Root NULL NULL Insert 7 Insert 3 5 5 Root Root 7 3 7 NULL NULL NULL NULL NULL NULL NULL
Rules, cont • The insertion rule is important to the functionality of the BST • This is what allows us to search in O(lg n) time • Removal is a little trickier
Removing nodes • If a node has 1 or less children (next nodes) it is similar to how we’ve done it with linked list • If left==right==NULL, the parent points to NULL (instead of the node we remove) • If left or right != NULL, but the other is NULL, the parent points to the non-NULL value • If both are != NULL, find the smallest value on the right subtree. Copy that value into our node. Remove “smallest value” from the right subtree. • This form of remove will call itself with a different “target” value
Traversal • There are three types of traversal which allow us to see the data in the tree • Preorder: NLR • Inorder: LNR • Postorder: LRN • N = look at node’s data • L = go left • R = go right • These traversals indicate the order we perform these three operations
Starting at root 5 3 7 5 Root R: 5 5 LR: 5 NLR: 5 Preorder - NLR Done 7 R: 7 LR: 7 NLR: 7 NLR: 3 LR: 3 3 R: 3 3 7 NULL NULL NULL NULL Nothing Nothing Nothing Nothing
Starting at root 3 5 7 5 Root R: 5 NR: 5 5 LNR: 5 Done Inorder - LNR 7 R: 7 NR: 7 LNR: 7 R: 3 LNR: 3 3 NR: 3 3 7 NULL NULL NULL NULL Nothing Nothing Nothing Nothing
Starting at root 3 7 5 5 Root N: 5 RN: 5 5 LRN: 5 Done Postorder - LRN 7 N: 7 RN: 7 LRN: 7 LRN: 3 RN: 3 3 N: 3 3 7 NULL NULL NULL NULL Nothing Nothing Nothing Nothing