π Lecture 17 β Reference Variables
π Overview: This lecture explains the concept of reference variables in C++ and how they differ from call by value and call by pointer mechanisms. Understanding reference variables is crucial for efficient function calls that avoid costly copying of large objects while maintaining clean syntax.
ποΈ Topics Covered
Reference variables are introduced as a mechanism to pass arguments to functions without making copies or using pointer syntax. The lecture compares three function calling methods: call by value, call by pointer, and call by reference, using detailed call stack diagrams to illustrate how each method affects the original variable. A sample program demonstrates these concepts with concrete examples.
π Lecture Summary
Reference Variables
The & symbol has two distinct uses in C++. When placed before a variable name (e.g., &x), it is the address operator that returns the memory address of that variable. When placed after the type in a function parameter (e.g., int& x), it declares a reference variable.
π Definition β Address Operator (&): Returns the memory address of the variable it precedes. For example, int* ptr = &x; stores the address of variable x in pointer ptr.
π Definition β Reference Variable: A parameter declared with & after its type (e.g., int& oldVal) that acts as an alias to the original variable passed from the calling function.
The lecture presents three function examples to illustrate different argument passing methods:
Function 1 - Call by Value (intMinus1):
int intMinus1( int oldVal) {
oldVal = oldVal β 1;
return oldVal;
}
This function takes an integer argument by value. A copy of the argument is made on the call stack.
Function 2 - Call by Pointer (intMinus2):
int intMinus2( int* oldVal) {
*oldVal = *oldVal β 2;
return *oldVal;
}
This function takes a pointer to integer as argument. The *oldVal notation is dereferencing, which accesses the value at the memory location pointed to by oldVal.
Function 3 - Call by Reference (intMinus3):
int intMinus3( int& oldVal) {
oldVal = oldVal β 3;
return oldVal;
}
The & after the type indicates this is a reference variable. No & or * is needed in the function body.
Internal Memory Organization of a Process
When a program runs, it becomes a process and is allocated a block of memory partitioned into several areas: Code (compiled binary), Static data (global/static variables), Stack (used for function calls), and Heap (dynamic memory allocation via new operator).
The call stack is used during function calls. When a function is called, an activation record is created containing parameters, local variables, and return address. A stack pointer (sp) points to the top of the stack.
Call Stack Analysis for intMinus1 (Call by Value)
When intMinus1(myInt) is called with myInt = 31, a copy of myInt (value 31) is placed on the stack as the parameter oldVal of the called function. The function subtracts 1 from oldVal (making it 30), but the original myInt in the caller remains unchanged at 31. After the function returns, the activation record is popped from the stack, and the return value (30) is assigned to retVal.
π Example: With myInt = 31, calling intMinus1(myInt) results in myInt = 31 and retVal = 30. The original variable remains unchanged.
π‘ Why this matters: Call by value protects the original data but creates copies, which can be inefficient for large objects.
Call Stack Analysis for intMinus2 (Call by Pointer)
When intMinus2(&myInt) is called, the address of myInt (1072) is passed as the pointer value. The function uses *oldVal = *oldVal β 2, which accesses the memory location 1072 (where myInt is stored) and changes its value from 31 to 29. Thus, myInt is permanently changed.
π Example: With myInt = 31, calling intMinus2(&myInt) results in myInt = 29 and retVal = 29. The original variable is modified.
Call Stack Analysis for intMinus3 (Call by Reference)
When intMinus3(myInt) is called, the reference variable oldVal becomes another name for the same memory location as myInt (address 1072). The statement oldVal = oldVal β 3 directly modifies myInt's value from 31 to 28. No copy is made on the stack; oldVal simply refers to the same memory location.
π Example: With myInt = 31, calling intMinus3(myInt) results in myInt = 28 and retVal = 28. The original variable is modified via an alias.
π Definition β Call by Reference: A function calling mechanism where the called function receives a reference (alias) to the original variable, allowing direct modification of the caller's variable without making copies or using pointer syntax.
Advantages of Reference Variables
Reference variables solve two problems: (1) Avoiding expensive copies of large objects (e.g., a 500-byte Customer object) that would consume stack space and time, and (2) Avoiding the complex syntax of pointers. The compiler implements reference variables internally using pointers, handling address calculation and dereferencing automatically behind the scenes.
π‘ Why this matters: For large objects, call by value creates costly copies on the stack. Reference variables provide the efficiency of pointers without the syntax complexity.
Sample Program
The lecture provides a complete program demonstrating all three calling methods with myInt = 31. The output confirms:
- intMinus1: retVal = 30, myInt = 31 (unchanged)
- intMinus2: retVal = 29, myInt = 29 (changed)
- intMinus3: retVal = 28, myInt = 28 (changed)
β Key Takeaways
The three function calling methodsβcall by value, call by pointer, and call by referenceβeach handle arguments differently in terms of copying, modification ability, and syntax. Call by value protects original data but creates copies. Call by pointer allows modification but requires complex syntax. Call by reference provides the efficiency of pointers without their complex syntax, making it ideal for passing large objects. The compiler implements references internally using pointers, so address manipulation happens behind the scenes. Understanding when to use each method is essential for writing efficient and readable C++ code, particularly when designing class interfaces that accept parameters.
π§ Quick Revision Questions
- What is the difference between
&x(address operator) andint& x(reference variable) in C++? - In call by value, what happens to the original variable in the calling function when the called function modifies its parameter?
- How does the call stack differ when passing a variable by pointer versus passing it by reference?
- Why might call by reference be preferred over call by value for passing large objects like a Customer class?
- What does the compiler do internally to implement reference variables, and how is this hidden from the programmer?
π Lecture 18 β Reference Variables, const Keyword, and Tips
π Overview: This lecture explores the pitfalls of storing references to transient objects in data structures and explains why dynamic memory allocation is necessary for objects that must persist beyond function scope. It also introduces the
constkeyword and its common uses in function signatures, along with practical tips for working with references in C++.
ποΈ Topics Covered
The lecture revisits reference variables and their behavior with the call stack, then demonstrates the problem of storing references to local (transient) objects in a queue. It explains how dynamic memory allocation on the heap solves this issue, and illustrates memory organization with stack and heap growth directions. Finally, it introduces the const keyword and provides several tips for using references safely.
π Lecture Summary
Reference Variables
In the last lecture we discussed about reference variables, seeing three examples: call by value, call by reference, and call by pointer. We saw the use of stack when a function is called by value, by reference, or by pointer. The arguments passed to the function and local variables are pushed onto the stack. There is one important point to note that in this course, we are using C/C++ but the usage of stack is similar in most computer languages like FORTRAN and Java. The syntax we are using here is C++ specific, like we are sending a parameter by pointer using & sign. In Java, native data types like int, float are passed by value and objects are passed by reference. In FORTRAN, every parameter is passed by reference. In PASCAL, you can pass a parameter by value or by reference like C++. You might have heard of ALGOL, which provided another way of passing parameters called call by name.
We have discussed when the variables are passed by reference then behind the scene what goes on inside the stack. There are few important things to take care of while using reference variables: One should be careful about transient objects that are stored by reference in data structures. We know that the local variables of a function are created on call stack. Those variables are created inside the function, remain in memory until the control is inside the function, and are destroyed when the function exits. The activation record comprises function call parameters, return address, and local variables. The activation record remains inside stack until the function is executing and is destroyed once the control is returned from the function.
Letβs see the following code that stores and retrieves objects in a queue:
void loadCustomer( Queue & q)
{
Customer c1("irfan");
Customer c2("sohail");
q.enqueue( c1 );
q.enqueue( c2 );
}
The above function loadCustomer(Queue &) accepts a parameter of type Queue by reference. Inside the function body, we create c1 and c2 Customer objects initialized to string values "irfan" and "sohail". Then we queue up these objects using the enqueue() method and the function returns. The objects created inside are local variables created on stack. In the Bank example, for each customer we have the name (32 characters maximum), arrival time (int type, 4 bytes), transaction time (int type), and departure time (int type), so the size of the Customer object is 44 bytes. The c1 and c2 objects are created on stack and have 44 bytes occupied. We are referring each 44 bytes of allocation with the name of the object.
Now consider the serviceCustomer() method:
void serviceCustomer( Queue & q)
{
Customer c = q.dequeue();
cout << c.getName() << endl;
}
The serviceCustomer(Queue &) also accepts one parameter of type Queue by reference. In the first statement, it takes out one element from the queue and assigns it to newly created object c. Before assignment, the object c is constructed by calling the default constructor. In the next statement, c.getName() function call is to get the name of the customer and then print it. This statement will not work. The reason is that objects c1 and c2 were created locally in loadCustomer() on stack. Their addresses (not the objects themselves) were added to the queue q. When loadCustomer() returned, the local objects c1 and c2 were destroyed but their addresses remained in the queue. When serviceCustomer() is called, the address of the object is retrieved from the queue and assigned to another local object c, but calling getName() using that retrieved address fails because the original object no longer exists.
This shows that using references alleviates the burden of copying objects, but storing references of transient objects (objects created on stack) can create problems because the transient object is destroyed when the function execution finishes.
π‘ Why this matters: Transient objects are destroyed when their function returns, so storing their addresses in data structures creates dangling references that cause program crashes.
The solution is dynamic memory allocation. All variables or objects created in a function that we want to access later are created on memory heap (sometimes called free store) using the new operator. Heap is an area in computer memory that is allocated dynamically. All objects created using new must be explicitly destroyed using the delete operator.
The modified code of loadCustomer():
void loadCustomer( Queue & q)
{
Customer * c1 = new Customer("irfan");
Customer * c2 = new Customer("sohail");
q.enqueue( c1 ); // enqueue takes pointers
q.enqueue( c2 );
}
This time, we create objects using the new operator and assign starting addresses to c1 and c2 pointers. Anonymous objects (objects accessed by pointers) are created. Here c1 and c2 are pointers to the objects, not the actual objects themselves. These starting addresses are queued using enqueue(). As the objects lie on the heap, there will not be any problem and the objects will be accessible after loadCustomer() returns.
The pointer variables c1 and c2 are created on stack and will be destroyed after loadCustomer()'s activation record is destroyed. The actual objects on heap persist. Since the starting addresses of the objects are put in the queue, they remain available to use later after retrieving them from the queue using dequeue(). These dynamic objects will live in memory (on heap) unless explicitly deleted.
π Definition β Heap (memory area): An area in computer memory given to a process from the operating system when the process does dynamic memory allocation.
The memory organization of a process includes: code section, static data section, stack (grows downward), and heap (grows upward). Stack grows downward and heap grows upward. An endless recursive call would cause the stack to grow and potentially overwrite the heap section. Endless dynamic memory allocation causes the heap to grow upward, potentially overwriting the stack. If a process has destructive code, it only causes its own destruction, not harming other processes. However, viruses often exploit stack overflow to change memory contents.
Consider allocating an array of 100 elements of Customer objects dynamically. Each object is 44 bytes, so the size of memory allocated on heap will be 4400 bytes (44 * 100). In the heap layout during call to loadCustomer, the object with string "irfan" is from memory address 600 to 643, and the object with name "sohail" is from address 644 to 687. When these objects are inserted in the queue, only their starting addresses (600 and 643) are inserted.
The serviceCustomer() function for dynamic objects:
void serviceCustomer( Queue & q)
{
Customer* c = q.dequeue();
cout << c->getName() << endl;
delete c; // the object in heap dies
}
We take a pointer out of the queue, call the method using -> operator, and then use delete to deallocate the object. This method executes successfully because the object was created dynamically inside loadCustomer().
π Definition β Dangling pointer: A pointer to an object that has already been deallocated or released. Accessing such a pointer (calling any of its members) may cause the program to crash.
The const Keyword
The const keyword is used for something to be constant. The actual meanings depend on where it occurs, but it generally means something is to be held constant. There can be constant functions, constant variables, or constant parameters.
References are pointers internally β they are constant pointers. You cannot perform any kind of arithmetic manipulation with references that you normally do with pointers. The const keyword is often used in function signatures (also called function prototypes), which mention the function name, its parameters, and return type.
Common uses of const:
- The
constkeyword appears before a function parameter. For example, in a chess program:
The functionint movePiece(const Piece & currentPiece)movePiece()is passed one parameter by reference. By writingconst, we are saying that the parameter must remain constant for the life of the function. If we try to change its value (e.g., the parameter appears on the left side of an assignment), the compiler will generate an error. This also means that if the parameter is passed to another function, that function must not change it either.
π Definition β const parameter: A function parameter that cannot be modified within the function or by any function it is passed to.
Use of const with reference parameters is very common. This is puzzling: why are we passing something by reference and then making it constant (don't change it)? Doesn't passing by reference mean we want to change it? The answer will be discussed in the next lecture.
Tips
β’ The arithmetic operations we perform on pointers cannot be performed on references.
β’ Reference variables must be declared and initialized in one statement.
β’ To avoid dangling reference, don't return the reference of a local variable (transient) from a function.
β’ In functions that return reference, return global, static, or dynamically allocated variables.
β’ Reference data types are used as ordinary variables without any dereference operator. We normally use arrow operator (->) with pointers.
β’ const objects cannot be assigned any other value.
β’ If an object is declared as const in a function, then any further functions called from this function cannot change the value of the const object.
β Key Takeaways
Storing references to transient (stack-allocated) objects in data structures causes problems because those objects are destroyed when the function exits, creating dangling references. To preserve objects beyond function scope, use dynamic memory allocation with the new operator to create objects on the heap; their addresses can then be safely stored in data structures. Remember that pointer variables themselves are destroyed when the function returns, but the heap-allocated objects persist until explicitly deleted with delete. The const keyword is used to make function parameters immutable, and it's commonly combined with reference parameters for efficiency without allowing modification. Avoid dangling references by never returning references to local variables.
π§ Quick Revision Questions
- What is a transient object and why is it problematic to store its reference in a data structure?
- How does dynamic memory allocation using
newsolve the problem of transient objects? - What is the difference between a pointer variable (created on stack) and the actual object it points to (created on heap)?
- Why might passing a parameter by reference with the
constkeyword be useful? - What is a dangling pointer and what can cause one?
π Lecture 19 β Data Structures
π Overview: This lecture explores the use of the
constkeyword in C++ to enforce programming discipline, examines the problem of degenerate binary search trees that form from sorted data, and introduces AVL trees as a self-balancing solution to maintain efficient search operations. Understanding these concepts is crucial for writing robust, efficient data structure implementations.
ποΈ Topics Covered
The lecture covers three main topics: the usage of the const keyword in function parameters, return types, and member functions to prevent unintended modifications; degenerate binary search trees that occur when data is inserted in sorted order, causing the tree to resemble a linked list; and AVL trees, which maintain balance by ensuring the height difference between left and right subtrees is at most 1 at every node.
π Lecture Summary
Usage of const keyword
The const keyword is used in several ways to enforce programming discipline and prevent accidental modifications. When passing parameters by reference, using const allows read-only access without copying the object. This is efficient because it avoids the time and memory overhead of creating a copy via the copy constructor, while ensuring the function cannot alter the original object. The calling function has read-only access to this object, using it in computation but not changing it.
π Definition β const reference parameter: A reference parameter declared with const that allows a function to access an object without copying it and without being able to modify it, providing both efficiency and safety.
When const appears at the end of a class member function signature, such as EType& findMin( ) const;, it indicates that the function cannot change or write to member variables of that class. These member variables, also called state variables, include items like root in the BinaryTree class or item in the node class. This constraint is important for functions that are supposed to read and return member variables without modification, like a getName method that returns a customer's name. The const keyword helps the compiler catch unintentional mistakes at compile time or runtime, enforcing discipline in programming.
When const appears at the beginning of the return type, as in const EType& findMin( ) const;, it returns a const reference to a member variable. Returning by reference avoids creating a copy of the object, which is important for large objects. However, a function should never return a reference to a local variable, as local variables are destroyed when the function ends. The const at the start ensures that the calling function cannot change the member variable value through this reference, protecting the object's integrity while still providing efficient access. The caller should use set methods if changes are needed.
π‘ Why this matters: Using const with references prevents expensive object copying while ensuring data integrity, making code both efficient and safe from unintended modifications.
Degenerate Binary Search Tree
Consider a BST created from the values 14, 15, 4, 9, 7, 18, 3, 5, 16, 20, 17. The root is 14, with smaller numbers in the left subtree and larger numbers in the right subtree, following the BST property. However, when data is provided in sorted order (3, 4, 5, 7, 9, 14, 15, 16, 17, 18, 20), the insert method creates a tree that looks like a linked list β each node has only a right child and no left child, forming a degenerate tree.
In this degenerate tree, searching for the value 20 requires traversing from 3 β 4 β 5 β 7 β 9 β 14 β 15 β 16 β 17 β 18 β 20, which is similar to linear search in a linked list. This defeats the purpose of a BST, where with one lakh numbers, a balanced tree would find any number in only 20 steps using the logarithmic property. The BST technique's benefit is lost because the tree is not balanced β the left and right subtrees do not have equal or similar heights.
To achieve balanced BST benefits, we need to keep the tree balanced. The ideal would be a complete binary tree where both left and right subtrees have the same height, requiring (2^(d+1) β 1) data items for a tree of depth d. However, this is impractical since we often cannot control the data input order.
AVL Tree
An AVL tree (named after Adelson-Velskii and Landis) is identical to a BST with two additional constraints: the height of left and right subtrees may differ by at most 1, and the height of an empty tree is defined to be (β1). The height of a binary tree is the maximum level of its leaves (also called the depth), calculated as the longest path from root to leaf.
The balance of a node is defined as the height of its left subtree minus the height of its right subtree. In an AVL tree, every node must have a balance of -1, 0, or 1. For example, in an AVL tree with root 5, left subtree height is 3 and right subtree height is 2, giving a difference of 1. At node 2, left subtree height is 1 and right subtree height is 2, also a difference of 1. At node 8, left subtree height is 1 and right subtree has height 0 (empty), giving a difference of 1. This condition must be satisfied at every node, not just the root.
In contrast, a non-AVL tree might have a node where left subtree height is 3 and right subtree height is only 1, giving a difference of 2. This violates the AVL condition. The AVL tree's balance factor at each node (shown as -1, 0, or 1) provides the information needed to maintain balance during insertions and deletions, ensuring the tree never degenerates into a linked list.
π Example: In the AVL tree with root 5, if the root's balance is -1, this means the right subtree's height is one greater than the left subtree's height. In the left subtree, a node with balance 1 indicates the left subtree's height is one greater than the right subtree's height. Nodes with balance 0 have equal left and right subtree heights.
β Key Takeaways
The most critical things to remember from this lecture: The const keyword serves three distinct purposes in C++ β preventing parameter modification via const reference, preventing member variable modification in const member functions (const at end of signature), and protecting returned references from being used to modify member variables (const at start of return type). Degenerate BSTs (resembling linked lists) occur when data is inserted in sorted order, destroying the logarithmic search performance that makes BSTs valuable. AVL trees solve this by enforcing a balance condition where the height difference between left and right subtrees at any node cannot exceed 1. The balance of a node is calculated as (height of left subtree - height of right subtree), and must always be -1, 0, or 1 for an AVL tree.
π§ Quick Revision Questions
- What are the three different ways the
constkeyword is used in C++ function signatures, and what does each one protect? - Why does inserting sorted data into a BST create a degenerate tree, and what is the search time complexity in such a tree?
- What is the definition of the balance of a node in a binary tree, and what values are allowed for a node in an AVL tree?
- A node in a tree has a left subtree of height 3 and a right subtree of height 1. Is this node AVL balanced? Why or why not?
- Why is requiring every node to have left and right subtrees of equal height (complete binary tree condition) impractical for real-world BST implementations?
π Lecture 20 β AVL Tree
π Overview: This lecture introduces the AVL tree, a self-balancing binary search tree named after its inventors Adelson-Velskii and Landis. It explains the concepts of height and balance, and details how to insert nodes while maintaining the tree's balance through rotations. Understanding AVL trees is crucial for ensuring efficient search operations in dynamic data structures.
ποΈ Topics Covered
The lecture covers the definition and properties of AVL trees, including the balance factor and height calculations. It then explains the conditions under which a tree becomes unbalanced after insertion, and introduces the rotation technique to restore balance. A step-by-step example of building an AVL tree by inserting numbers 1, 2, and 3 is provided, demonstrating the rotation process.
π Lecture Summary
AVL Tree
In 1962, Russian scientists Adelson-Velskii and Landis proposed criteria to prevent a binary search tree from becoming degenerate, developing the AVL tree (an acronym of their names). An AVL tree is identical to a BST, with one key difference: the height of the left and right subtrees can differ by at most 1. The height of an empty tree is defined as (β1). The balance (also called balance factor) of a node is the difference between the height of its left subtree and the height of its right subtree. In an AVL tree, the balance of any node must be 1, 0, or β1, depending on whether the left subtree is taller, equal, or shorter than the right subtree.
π Definition β AVL Tree: A binary search tree where, for every node, the height of the left and right subtrees differ by at most 1. π Formula: Balance = Height of Left Subtree β Height of Right Subtree β A value of 1, 0, or -1 is acceptable. π Example: In a tree with root node 5, if the deepest node in the left subtree (node 3) is at level 3, the height of the left subtree is 3. If the deepest node in the right subtree (node 7) is at level 2, the height of the right subtree is 2. The balance of node 5 is 3 β 2 = 1, which is acceptable. However, for a tree to be an AVL tree, every node must satisfy this condition.
Height
The height of a binary tree is the maximum level of its leaves. This is the same definition as the depth of a tree.
π Definition β Height: The maximum level of any leaf node in a binary tree.
Balance
The balance of a node in a binary search tree is defined as the height of its left subtree minus the height of its right subtree. At a particular node, the difference in heights of its left and right subtrees gives the balance of the node.
π Definition β Balance: The height of the left subtree minus the height of the right subtree for a given node.
Insertion of Node in an AVL Tree
When inserting a new node into an AVL tree, we must ensure that the tree remains balanced. The new node is always inserted as a leaf node. The tree becomes unbalanced only if the newly inserted node:
- Is a left descendant of a node that previously had a balance of 1.
- Or is a descendant of a node that previously had a balance of β1. The first condition occurs because a node with balance 1 has a left subtree 1 level deeper than its right subtree. Adding a node to this left subtree increases its height by 1, making the difference 2. Similarly, a node with balance β1 has a right subtree 1 level deeper. Adding a node to this right subtree makes the balance β2.
π‘ Why this matters: When insertion violates the AVL condition, we must reorganize the tree to restore balance while maintaining the same inorder traversal order. This process is called rotation.
π Definition β Rotation: A tree modification process that restores balance to a node after an insertion violates the AVL condition, while preserving the inorder traversal order of the data. π Example: Consider a tree where node A has balance 1, node B is its left child with balance 0, and a new node is inserted into T1 (left subtree of B). After insertion, the balance of A becomes 2 and B becomes 1. To fix this, we make B the new root, A becomes the right child of B, and T2 (right subtree of B) becomes the left subtree of A. The inorder traversal remains T1 B T2 A T3 in both cases.
Example (AVL Tree Building)
Let's build an AVL tree by inserting numbers 1, 2, and 3, checking the balance after each insertion and applying rotations when necessary.
Step 1: Insert 1. The tree has one node (1). No balance issues.
Step 2: Insert 2. Since 2 > 1, it becomes the right child of 1. The tree has nodes 1 (root) and 2 (right child). No balance issues yet.
Step 3: Insert 3. Since 3 > 1 and 3 > 2, it becomes the right child of 2. The tree now has nodes 1 (root at level 0), 2 (level 1), and 3 (level 2). The left subtree of node 1 has height 0, and its right subtree has height 2 (deepest node 3 at level 2). The balance of node 1 is 0 β 2 = β2, violating the AVL condition. We apply a left rotation at nodes 1 and 2. Node 2 becomes the new root, node 1 becomes its left child, and node 3 remains its right child. After rotation, the tree is balanced with all nodes having balance 0, and the inorder traversal is still 1 2 3.
π Example: Inserting 1, 2, 3 into an AVL tree. Before rotation: root 1 (balance -2), right child 2, right child 3. After left rotation: root 2 (balance 0), left child 1 (balance 0), right child 3 (balance 0).
β Key Takeaways
An AVL tree maintains balance by ensuring the height difference between left and right subtrees of any node is at most 1, with balance factors of 1, 0, or -1. When an insertion violates this rule, rotation is applied to reorganize the tree and restore balance while preserving the inorder traversal order. The tree becomes unbalanced only when a new node is inserted as a descendant of a node with a balance factor of 1 (left subtree) or -1 (right subtree). The rotation process can be demonstrated with a simple example like inserting 1, 2, and 3, where a left rotation fixes the imbalance at node 1. The critical point is that different tree structures can produce the same sorted inorder traversal, allowing flexible rearrangement during balancing.
π§ Quick Revision Questions
- What is the maximum allowed difference between the heights of the left and right subtrees of any node in an AVL tree?
- How is the balance factor of a node calculated?
- Under what specific conditions does an AVL tree become unbalanced after inserting a new node?
- What operation is used to restore balance in an AVL tree after an insertion violates the condition, and what key property of the tree must be preserved?
- In the example of inserting numbers 1, 2, and 3, what was the balance factor of node 1 before rotation, and what rotation was applied to fix it?
π Lecture 21 β AVL Tree Building Example & Cases for Rotation
π Overview: This lecture continues building an AVL tree through example, demonstrating how nodes are inserted and rotated to maintain balance. It introduces the four cases of rotation violations and explains why single rotation works for some cases (left-left and right-right) but fails for others (left-right and right-left), setting up the need for double rotation.
ποΈ Topics Covered
The lecture covers a step-by-step AVL tree building example with nodes 3 through 16, calculating balance factors after each insertion and performing rotations when violations occur. It then formally categorizes the four cases of rotation violations and demonstrates with diagrams why single rotation fixes cases 1 and 4 (outside insertions) but not cases 2 and 3 (inside insertions).
π Lecture Summary
AVL Tree Building Example
This lecture continues building an AVL tree from the previous lecture, starting after inserting node 3. The tree after inserting 3 with a single left rotation has node 2 as the root, with node 1 as its left child and node 3 as its right child.
Inserting node 4: Compare with root node 2 β since 4 > 2, go right to node 3, then 4 > 3, so 4 becomes right child of 3. After insertion, check balance factors: node 4 has balance factor 0, node 3 has balance factor β1 (no left child, right subtree exists), node 1 has 0, and node 2 has balance factor 1 β 2 = β1. All nodes have balance factors within {0, 1, β1}, so the tree remains AVL.
π Definition β Balance Factor: The height of the left subtree minus the height of the right subtree. For an AVL tree, every node's balance factor must be 0, 1, or β1.
Inserting node 5: The new node 5 becomes right child of node 4. Balance factors: node 5 = 0, node 4 = β1, node 3 = β2. Since node 3 has balance factor β2, a rotation is required. After a single left rotation on node 3, node 4 becomes the right child of node 2, and node 3 becomes the left child of node 4. All nodes now have balance factors of 0 or β1.
π Key observation β Inorder Traversal Preserved: Before rotation, inorder traversal of the tree in Fig 21.4 gives: 1 2 3 4 5. After rotation, the inorder traversal of Fig 21.5 also gives: 1 2 3 4 5. The rotation operation preserves the inorder traversal of the tree.
Inserting node 6: Node 6 becomes right child of node 5. Balance factors: node 6 = 0, node 5 = β1, node 3 = 0, node 4 = β1, node 1 = 0, node 2 = β2 (left subtree height 1, right subtree height 3). Root node 2 requires rotation. After rotation, node 4 becomes the new root, node 2 becomes left child of node 4, node 3 (formerly left child of node 4) becomes right child of node 2. Inorder traversal: 1 2 3 4 5 6.
π‘ Why this matters: In a BST, the root node remains the same (the first inserted node). In an AVL tree, the root node keeps changing through rotations to maintain balance. This balancing ensures search efficiency β in an AVL tree built of n items, you can search up to 1.44 logβ n levels maximum, compared to a linked list BST where you might traverse nβ1 links.
Inserting node 7: Node 7 becomes right child of node 6. Balance factors: node 7 = 0, node 6 = β1, node 5 = β2. After rotation on node 5, node 5 becomes left child of node 6. The resulting tree is a perfect balanced binary tree β all nodes (7, 5, 3, 1, 6, 2, 4) have balance factor 0. Inorder traversal: 1 2 3 4 5 6 7.
Inserting node 16: Node 16 becomes right child of node 7. Balance factors for all nodes (16, 7, 5, 3, 1, 6, 2, 4) are 0 or β1. The tree remains AVL.
Inserting node 15: Node 15 becomes left child of node 16. Balance factors: node 5 = 0, node 16 = 1 (within limits), but node 7 = β2 (violation). A single left rotation on node 7 makes node 7 the left child of node 16, and node 15 becomes right child of node 7. However, after this rotation, balance factors are: node 15 = 0, node 7 = β1, node 16 = 2. The single rotation did not fix the imbalance β node 16 still has balance factor 2, which is outside AVL limits.
Cases for Rotation
When a node Ξ± requires rebalancing (balance factor Β±2), since any node has at most two children and the height imbalance requires Ξ±'s two subtrees to differ by 2 (or β2), the violation occurs in four cases:
- An insertion into left subtree of the left child of Ξ± (left-left case)
- An insertion into right subtree of the left child of Ξ± (left-right case)
- An insertion into left subtree of the right child of Ξ± (right-left case)
- An insertion into right subtree of the right child of Ξ± (right-right case)
The insertion occurs on the outside in cases 1 and 4 (left-left or right-right). Single rotation can fix the balance in cases 1 and 4.
The insertion occurs on the inside in cases 2 and 3 (left-right or right-left). A single rotation cannot fix these cases.
Case 1 (Single Right Rotation): Node kβ is the root (Ξ±), kβ is its left child, Z is its right child. X and Y are left and right subtrees of kβ. A new node is inserted as a child of X (outside insertion). A single right rotation makes kβ the new root, kβ becomes the right child of kβ, and Y becomes the left child of kβ. Inorder traversal: X kβ Y kβ Z (preserved).
Case 4 (Single Left Rotation): A new node is inserted as a child of Z (right subtree of the right child of the root Ξ±). A single left rotation on node kβ makes kβ rotate left. Node Y becomes the right child of node kβ.
Case 2 (Single Right Rotation Fails): A new node is inserted below node Y (inside insertion β right subtree of left child). After insertion, balance factor for node kβ becomes 2. A single right rotation on kβ produces balance factor for kβ of β2. The tree remains unbalanced because the node Y subtree is unchanged β it changes its parent node but its subtree remains intact.
π Formula β Maximum Height of AVL Tree: 1.44 logβ n, where n is the number of nodes in the tree. This guarantees efficient search operations.
β Key Takeaways
The most critical concepts from this lecture are that AVL trees maintain balance through rotations performed immediately after insertions when any node's balance factor reaches Β±2. Single rotations (left or right) successfully fix violations from outside insertions (left-left and right-right cases), but fail for inside insertions (left-right and right-left cases) because the problematic subtree (Y in case 2, or its mirror in case 3) remains unchanged through single rotation. The inorder traversal of the tree is always preserved during rotations, ensuring the binary search tree property is maintained. In an AVL tree, the root changes dynamically through rotations, achieving a maximum search depth of 1.44 logβ n, which is significantly better than the worst-case linked list structure of a simple BST.
π§ Quick Revision Questions
- What are the four cases of rotation violations in an AVL tree, and which two can be fixed by a single rotation?
- After inserting node 6 into the AVL tree, why was node 2 (the root) rotated instead of node 3 or node 4?
- In the example of inserting node 15 (Fig 21.11 to Fig 21.12), why did the single left rotation on node 7 fail to restore balance?
- What happens to the inorder traversal sequence when a rotation is performed on an AVL tree?
- What is the maximum number of levels (links) you need to traverse to search for a node in an AVL tree built of n items?
π Lecture 22 β Cases of Rotations and Double Rotations in AVL Trees
π Overview: This lecture addresses situations where single rotations fail to restore balance in an AVL tree, specifically when the new node is inserted in the "inside" subtrees. It introduces the left-right and right-left double rotations to fix these cases and presents the complete C++ code for the
avlInsertmethod, including balance checks and rotation logic.
ποΈ Topics Covered
The lecture begins by reviewing the four insertion scenarios where single rotation fails for inside insertions (cases 2 and 3). It then analyzes the problematic case 2, expands nodes to understand the structure, and introduces the left-right double rotation by performing two single rotations. The symmetric case 3 (right-left double rotation) is similarly addressed. Finally, the lecture presents the complete C++ code for the avlInsert method, including height calculations, balance factor checks, and conditional calls to single or double rotation routines while preserving inorder traversal.
π Lecture Summary
Cases of rotations
The lecture revisits the four insertion scenarios relative to the Ξ± node. In case-1 (new node in left subtree of Ξ±'s left child) and case-4 (new node in right subtree of Ξ±'s right child), single rotation restores balance. However, in case-2 (new node in right subtree of Ξ±'s left child) and case-3 (new node in left subtree of Ξ±'s right child), single rotation fails. The figure shows an Ξ± node k2 with left child k1 (with children X and Y) and right child Z. The new node is inserted under Y. After applying single right rotation, the tree remains unbalanced because the difference between left and right subtree levels at the new root k1 is still 2.
Left-right double rotation to fix case 2
To solve case 2, the lecture expands the Y subtree to show its root k2 and subtrees B and C. The tree now has three nodes (k1, k2, k3) and four subtrees (A, B, C, D). The new node is inserted either in B or C, making one of these subtrees two levels deeper than D. The inorder traversal of the original tree is A, k1, B, k2, C, k3, D. Since single rotation (making k1 or k3 the root) fails, the solution is to make k2 the new root. This is achieved through a double rotation: first, perform a left rotation between k1 and k2. This makes k2 the left child of k3, and subtree B becomes the right child of k1. Second, perform a right rotation between k2 and k3. This makes k2 the root, k1 its left child, and k3 its right child. The final inorder traversal is A, k1, B, k2, C, k3, D, preserving the original order and restoring balance.
Right-left double rotation to fix case 3
Case 3 is symmetric: the new node is inserted in the left subtree of the right child. Here, k1 is the root, k3 is its right child, and k2 is the inner child. The new node is inserted in k2's left (B) or right (C) subtree. To make k2 the root, first perform a right rotation between k2 and k3, bringing k2 up and making k3 its right child while subtree B stays with k2 and C attaches to k3. Then perform a left rotation between k1 and k2, making k2 the root with k1 as left child and k3 as right child. The inorder traversal is preserved.
The lecture revisits the example tree containing numbers 1 through 7 and 16. When inserting 15 as the left child of 16, it creates a case requiring right-left double rotation. After right rotation on the link of 15 and 16 (promoting 15 up and 16 down), then left rotation on the link of 7 and 15, the tree becomes balanced with 15 as root of the subtree and 7 and 16 as left and right children. The AVL condition is fulfilled: at node 4, left depth is 2 and right depth is 3 (difference = 1); at node 6, left depth is 1 and right depth is 2 (difference = 1). The resulting tree is balanced, and the height becomes 1.44 logβ n in the worst case, ensuring logarithmic search time.
π‘ Why this matters: The balanced nature of the AVL tree prevents the degenerate linked-list structure that occurs with sorted data, keeping search operations efficient at approximately logβ(10 million) levels even with ten million nodes.
The lecture continues inserting 14, which becomes the right child of 7 β an inner subtree of 15. This again requires double rotation (right-left). After right rotation between 14 and 15, then left rotation between 7 and 15, the tree balances with 7 as root, 4 and 15 as its left and right children. Inorder traversal (1, 2, 3, 4, 5, 6, 7, 14, 15, 16) remains sorted.
Inserting 13 requires only a single left rotation. The final tree has root 7, with left subtree containing 4, 2, 1, 3, 6, 5 and right subtree containing 15, 14, 13, 16. The tree remains balanced throughout the insertion process β it is not just balanced at the end, but at every step, the difference in levels between any node's right and left subtrees never exceeds 1.
C++ Code for avlInsert method
The lecture presents the complete C++ code for the avlInsert function, which incorporates balancing during insertion.
Function signature:
TreeNode<int>* avlInsert(TreeNode<int>* root, int info)
Logic:
-
If
info < root->getInfo(), insert into left subtree via recursive call:root->setLeft(avlInsert(root->getLeft(), info)). After insertion, calculate height difference:int htdiff = height(root->getLeft()) - height(root->getRight()). Ifhtdiff == 2, check whether the info is inserted in the outside subtree (info < root->left->info β single right rotation) or inside subtree (else β double left-right rotation). -
If
info > root->getInfo(), insert into right subtree similarly. Calculate:int htdiff = height(root->getRight()) - height(root->getLeft()). Ifhtdiff == 2, check if info > root->right->info (outside, case 4 β single left rotation) or else (inside, case 3 β double right-left rotation). -
If
info == root->getInfo(), the value already exists. After all cases, update height:int ht = Max(height(root->getLeft()), height(root->getRight())); root->setHeight(ht + 1); return root.
The function returns the root (which may change due to rotations). The rotation routines (singleRightRotation, singleLeftRotation, doubleLeftRightRotation, doubleRightLeftRotation) are not shown in code but are described conceptually.
β Key Takeaways
The most critical concepts from this lecture are: (1) Single rotations fix only "outside" insertions (left-left and right-right cases), while double rotations (two single rotations in sequence) are required for "inside" insertions (left-right and right-left cases). (2) The double rotation for case 2 (left-right) involves a left rotation between the lower node and middle node, followed by a right rotation between the middle node and Ξ± node, making the formerly middle node the new root. (3) The double rotation for case 3 (right-left) is symmetric, involving a right rotation first then a left rotation. (4) The avlInsert method recursively inserts a node, calculates the balance factor at each node, and performs the appropriate single or double rotation only at the node where the balance factor becomes 2, preserving inorder traversal and AVL balance. (5) The height of an AVL tree is at most 1.44 logβ n, guaranteeing logarithmic search time regardless of insertion order.
π§ Quick Revision Questions
- In case 2 of AVL insertion (new node in right subtree of Ξ±'s left child), why does single rotation fail, and how does a left-right double rotation solve the problem?
- What are the two single rotations performed in a right-left double rotation (case 3), and which nodes become the new root, left child, and right child after the rotation?
- In the
avlInsertcode, how does the algorithm determine whether to perform a single rotation or a double rotation when the balance factor becomes 2? - What is the worst-case height of an AVL tree, and why does this make search operations efficient even with millions of nodes?
- In the example tree with nodes 1 through 7 and 16, what rotation(s) were required when inserting node 14, and what was the final shape of the tree after all insertions?