120 likes | 138 Views
Learn about AVL trees and 2-3 trees, two self-balancing data structures in .CS.240. Explore the algorithms for balancing and insertion, along with recursion and proving algorithms.
E N D
CS 240: Data Structures Tuesday, July 29th 2-3 Trees, Proving Algorithms
Self-Balancing Trees • AVL: A self-balancing tree that uses a “balance” factor to determine if an adjustment is needed. • Each node is created with the balance factor set to 0. • Balance is equal to the difference between the height/depth of a node’s sub-trees. • Rebalance occurs whenever one of the 4 cases exists.
AVL Cases • Left-Left: Parent = -2, Left Child – 1 • Rotate Right around Parent • Left-Right: Parent = -2, Left Child = +1 • Rotate left around child, right around Parent • Right-Right: Parent = +2, Right Child = +1 • Rotate Left around Parent • Right-Left: Parent = +2, Right Child = -1 • Rotate right around child, left around Parent.
AVL • This works out rather well. • However, almost half of insertions and removal require rotation.
Recursion • Activation Stack: • This is a model for evaluating recursion. Let’s take a look at it: • Factorial • Fibonacci • Power
2-3 Trees • 2-3 Trees are a special type of tree intended to be self-balancing. • Terms: • 2-Node: A node with 1 value, 2 links • 3-Node: A node with 2 values, 3 links
2-Node Left is less than Right is greater than 3-Node Left is less than first value Right is greater than right value Middle is between the two values 15 13, 45
Insertion rules: • If root==NULL, insert at root as a 2-node • If we are at a leaf: • If 2-Node, insert here – turn into 3-Node • Else: split 3-Node into 2 2-Nodes, pass the parent and left child up one level • The textbook says right child for some reason… • Otherwise, non-leaf, take appropriate path.
Proving Algorithms double power(double x, int exponent) { if(exponent==0) { return 1.0; } return x*power(x,exponent-1); } • Conditions: X is real, exponent is non-negative • First identify cases Base Case Inductive Case
Validate the base case: • When exponent==0, x0 == 1.0 • We externally know this is true • Consider the case where exponent is k. • Then, we expect that power(x,k) == xk • Let us solve for power(x,k+1) • By replacement: • return x * power(k) x * xk
Lets do this for some other functions: • size, factorial, any others?
Test Material • The test is comprehensive reflecting material throughout the course. • Now is the time to ask about any particulars of the test. • Good luck!