220 likes | 304 Views
Week 8 - Monday. CS221. Last time. What did we talk about last time? BST traversals. Questions?. Assignment 4. Project 3. Student Lecture: Breadth First Traversal. Breadth First Search. What if we didn’t have a BST?.
E N D
Week 8 - Monday CS221
Last time • What did we talk about last time? • BST traversals
What if we didn’t have a BST? • Maybe we still have a binary tree, but we don’t have any guarantees about ordering • How would you search for something? • We could use preorder or postorder traversals • These are types of depth first searches • You go to the bottom of the tree before you come back • What if we thought what we are looking for might be close to the top?
Level order traversal 10 • The most logical breadth first traversal visits each level of a tree in order: • 10 6 14 1 9 17 2 7 15 6 14 1 9 17 2 7 15
Breadth first search and dating From: http://xkcd.com/761/
Breadth first algorithm • For depth first traversals, we used a stack • What are we going to use for a BFS? • A queue! • Algorithm: • Put the root of the tree in the queue • As long as the queue is not empty: • Dequeue the first element and process it • Enqueue all of its children
Breadth first implementation • Write a level order (breadth first) traversal • Hint: Use an explicit queue • Non-recursive! public voidlevelOrder()
Delete private static Node remove(Node node, int key) Proxy: public voidremove(intkey) { root = remove( root, key ); } • Find the node • Find its replacement (smallest right child or largest left child) • Swap out the replacement We may need some subroutines: private static Node smallest(Node node, Node parent) private static Node largest(Node node, Node parent) Note: This can cause an unbalanced tree.
AVL Tree Balance in all things
Problem! • Adding nodes arbitrarily to a binary search tree can make it unbalanced • If it’s unbalanced, it might not be any better than a linked list, yet takes more space • There are a number of ways to do this • A classic is an AVL tree • Named for its inventors G.M. Adelson-Velskii and E.M. Landis • Invented in 1962
AVL definition • An AVL tree is a binary search tree where • The left and right subtrees of the root have heights that differ by at most one • The left and right subtrees are also AVL trees
Balance factor • The book defines balance factor of a tree as the height of the rightsubtree minus the height of the leftsubtree • Thus, you can find the balance factor at every node of the tree • If any node has a balance factor more than 1 or less than -1, it's not AVL
AVL tree? 10 6 14 1 9 17 2 7 15
Next time… • Building AVL trees • Balancing trees by construction
Reminders • Start working on Project 3 • Start working on Assignment 4 • Keep reading Chapter 6