0% found this document useful (0 votes)
3 views

DataStructure_Midterms_Reviewer

The document provides an overview of stack and queue data structures, detailing their principles, operations, and implementations. It covers key concepts such as the LIFO principle for stacks and FIFO principle for queues, along with exception handling and dynamic implementations using linked nodes. Additionally, it discusses applications of these data structures, including employee records management and expression evaluation.

Uploaded by

2242405
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DataStructure_Midterms_Reviewer

The document provides an overview of stack and queue data structures, detailing their principles, operations, and implementations. It covers key concepts such as the LIFO principle for stacks and FIFO principle for queues, along with exception handling and dynamic implementations using linked nodes. Additionally, it discusses applications of these data structures, including employee records management and expression evaluation.

Uploaded by

2242405
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Data Structures Effect of a Pop operation

Lesson 1: Stack Data Structure


Overview
• The Stack Data Structure follows the Last In First Out
(LIFO) principle.
o Alternatively, it can be described as First In
Last Out (FILO).
• Items are added and removed from one side called
the top.
Key Operations
• Push: Adds an item to the top of the stack.
• Pop: Removes the item from the top of the stack.

Stack Interface and Implementation


Typical Stack Interface for Dynamic Implementation
Implementations of Stack Interface Definition
1. Array-based Stack (Static Implementation)
o Uses a fixed-size array to store elements. The Stack interface defines the basic operations for a stack
o Limits the number of items due to a fixed data structure in a dynamic implementation.
maximum size.
2. Linked Node-based Stack (Dynamic public interface Stack<T> {
Implementation) public int size();
o Uses linked nodes for storing elements. public boolean isEmpty();
o Can grow or shrink as needed. public T peek() throws StackException;
o The maximum size is limited only by the public T pop() throws StackException;
available memory. public void push(T item) throws StackException;
}

Exception Handling for Stack


Basic Stack Operations User-Defined Exception: StackException
• Push: Insert an element at the top.
• Pop: Delete the top element. A custom exception to handle stack-specific errors like
underflow and overflow.

public class StackException extends RuntimeException {


Additional Operations public StackException(String errorMessage) {
• Size: Get the current count of elements in the stack. super(errorMessage);
• isEmpty: Check if the stack is empty. }
• Peek: View the top element without removing it. }

Sequential Stack Stack Implementations


1. Sequential Representation (Array-Based)
• Uses an array to represent a stack with a maximum
size of n.
• Conditions:
o Empty Stack: top = -1
o Full Stack: top = n - 1
• Exceptions:
o Underflow: Occurs when trying to delete
from an empty stack.
Effect of a Push operation o Overflow: Occurs when trying to insert into
a full stack.

2. Linked Representation (Dynamic Structure)


• Uses a linked list of ListNode<T> objects to
implement a stack.
• Allows dynamic growth and shrinkage without a
fixed size limit.
• Suitable for situations where the stack size may vary
significantly.
Linked Stack Implementation this.data = data;
Implementation: LinkedStack this.link = link;
}
The LinkedStack class provides a dynamic stack
implementation using linked nodes. public void setData(E data) {
this.data = data;
public class LinkedStack<T> implements Stack<T> { }
private ListNode<T> top;
private int numElements = 0; public void setLink(MyStackNode<E> link) {
this.link = link;
public int size() { }
return numElements;
} public E getData() {
return data;
public boolean isEmpty() { }
return top == null;
} public MyStackNode<E> getLink() {
return link;
public T peek() throws StackException { }
if (isEmpty()) }
throw new StackException("Stack is empty.");
return top.getInfo();
} Possible Template for a Dynamic Stack

public T pop() throws StackException {


if (isEmpty())
throw new StackException("Stack underflow.");
ListNode<T> temp = top;
top = top.getLink();
numElements--;
return temp.getInfo();
}

public void push(T item) throws StackException {


ListNode<T> newNode = new ListNode<T>();
newNode.setInfo(item);
newNode.setLink(top);
top = newNode;
numElements++;
}

// Additional methods or functionalities can be added here Understanding the Fundamentals of the Dynamic Stack Data
} Structure

Stack Interface Definition

Template of a Node in a Dynamic Stack MyStackInterface

This interface defines the fundamental operations for a


dynamic stack.

public interface MyStackInterface<E> {


public int size();
public boolean isEmpty();
public E pop() throws StackException;
public void push(E item) throws StackException;
public E peek() throws StackException;
}

Dynamic Stack Implementation


MyDynamicStack Class
The MyDynamicStack class implements the MyStackInterface
Node Implementation for a Dynamic Stack
and represents a dynamic stack using linked nodes.
MyStackNode Class

The MyStackNode class represents a node used in the


public class MyDynamicStack<E> implements
implementation of a dynamic stack. It stores an element's
MyStackInterface<E> {
data and a reference (link) to the next node in the stack.
private MyStackNode<E> top;
private MyStackNode<E> first;
public class MyStackNode<E> {
private E data;
public MyDynamicStack() {
private MyStackNode<E> link;
top = null;
first = null;
public MyStackNode(E data, MyStackNode<E> link) {
}
Simplified Reference Class for an Employee
public MyDynamicStack(MyStackNode<E> node) { Employee Class Definition
top = node;
first = node; The following class serves as a simple representation of an
} employee record.

public void setTop(MyStackNode<E> node) {


top = node;
}

public void setFirst(MyStackNode<E> node) {


first = node;
}

public MyStackNode<E> getTop() {


return top;
}

public MyStackNode<E> getFirst() {


return first;
} Simplified Reference Class for an Employee
Employee Class Definition
public boolean isEmpty() { The Employee class represents an employee record and
return (top == null); implements the Comparable interface for comparison
} purposes.

public void push(E data) { public class Employee implements Comparable<Employee> {


MyStackNode<E> node = new MyStackNode<E>(data, private String idNumber;
null); private String name;
if (top == null) {
top = node; public Employee(String num, String name) {
first = node; this.idNumber = num;
} else { this.name = name;
top.setLink(node); }
top = node;
} public void setIdNumber(String n) {
} this.idNumber = n;
}
// Other methods (pop, peek, size) can be included here
} public String getIdNumber() {
return idNumber;
}

User-Defined Exception Class public String getName() {


StackException return name;
A custom exception class to handle stack-specific errors. }

// Additional methods can be included here


public class StackException extends RuntimeException {
public StackException(String description) { @Override
super(description); public int compareTo(Employee other) {
} return this.idNumber.compareTo(other.idNumber);
} }
}

Sample Application of the Stack Data Structure


Use Case: Employee Records Management Lesson 2: Infix to Postfix
The Stack data structure can be utilized to manage employee Applications of the Stack
records, facilitating a Last In First Out (LIFO) policy during Stacks are versatile data structures that can be applied in
retrenchment processes. This approach ensures that the most various scenarios. Here are some key applications:
recently hired employees are the first to be considered for 1. Pattern Recognition Problem
layoffs, aligning with lawful practices for reducing workforce o Stacks can be used to manage sequences
size. and check for patterns in data.
2. Evaluation of Expressions
Advantages of Using Stack for Employee Records o Stacks facilitate the evaluation of
• Easy Access: Allows quick retrieval and management mathematical expressions, especially in
of the most recently added employee records. converting infix expressions to postfix
• Order of Operations: Ensures that the last employee (Reverse Polish Notation) and evaluating
added to the stack is the first to be removed, them.
adhering to the LIFO principle. 3. Handling Recursive Calls
o Stacks are used to keep track of function
calls in recursion, managing the return
addresses and local variables.
Advantages of Postfix Representation
• No parentheses are needed when applying
Flow of Palindrome Recognition using a stack precedence rules.

Evaluating a Postfix Expression


• Each operator in a postfix expression operates on the
two most recent operands.
• One operand may be the result of a previous
operation.

Queue Data Structures


Queue Overview
• Queue Data Structure:
o A linear collection of elements processed
using the First-In, First-Out (FIFO) principle.
Forms of Expressions in Programs o Also referred to as Last-In, Last-Out (LILO).
Types of Expressions Characteristics
• Infix Expression • The queue operates like a line, where the first
• Prefix Expression element added is the first to be removed.
• Postfix Expression
Example: Summing A and B
• Infix Representation: A + B
• Prefix Representation: +AB Linked Representation of the QUEUE
• Postfix Representation: AB+

Role of Operator Precedence


When converting an infix expression with multiple operators
to postfix or prefix, understanding operator precedence is
essential.

Operator Precedence
• Operators:
o + for addition
o - for subtraction
Popular/Conventional Terms Associated with the Queue
o * for multiplication
Data Structure
o / for division
o $ for exponentiation
Conventional Terms
• Precedence Levels (from highest to lowest):
• Front: Reference to the first (oldest) element in the
o Exponentiation
queue.
o Multiplication / Division
• Rear: Reference to the last (newest) element in the
o Addition / Subtraction
queue.
General Rule • Head: Alternative term for the front of the queue.
• Consecutive operators with the same precedence are • Tail: Alternative term for the rear of the queue.
applied from left to right, except for exponentiation, • Enqueue: Operation for adding an element to the
which is applied from right to left. queue (at the tail/rear).
• Dequeue: Operation for removing an element from
Exponentiation in Java the queue (from the head/front).
• Java does not have a built-in exponentiation
operator. Instead, exponentiation is implemented as
a method.
Template for the Node of a Linked Representation of the
Queue
QueueNode Class Definition
Examples of Infix to Postfix Conversion
public class QueueNode<T> {
Example 1 T info;
• Infix: A + B * C QueueNode<T> link;
o Conversion Steps:
public QueueNode(T info, QueueNode<T> link) {
▪ A + B * C → A + BC* → ABC*+
o Postfix: ABC*+ this.info = info;
Example 2 this.link = link;
}
• Infix: (A + B) * C
}
o Conversion Steps:
▪ (A + B) * C → AB+ * C → AB+C*
o Postfix: AB+C*
Linked Representation of the Queue Topological Sorting – An Application
Characteristics Overview
• A queue is empty if both front and rear are null. • Input: Partially ordered elements.
• Overflow occurs only when the program runs out of • Output: A list of elements where no element is listed
memory. with its predecessor that has not yet appeared in the
output.

Partial Ordering Properties


1. Transitivity: If x⪯yx \preceq yx⪯y and y⪯zy \preceq
Sequential Representation of the Queue zy⪯z, then x⪯zx \preceq zx⪯z.
Characteristics 2. Antisymmetry: If x⪯yx \preceq yx⪯y and y⪯xy
• Utilizes a one-dimensional array/vector. \preceq xy⪯x, then x=yx = yx=y.
• A queue is empty if front = rear and full if front = 0 3. Reflexivity: x⪯xx \preceq xx⪯x.
and rear = n. 4. Corollaries:
• Exceptions: o If x⪯yx \preceq yx⪯y and x≠yx \neq yx =y,
o Deletion from an empty queue causes an then x≺yx \prec yx≺y.
underflow. o Transitivity: If x≺yx \prec yx≺y and y≺zy
o Insertion onto a full queue causes an \prec zy≺z, then x≺zx \prec zx≺z.
overflow. o Asymmetry: If x≺yx \prec yx≺y, then y⊀xy
\nprec xy⊀x.
o Irreflexivity: x⊀xx \nprec xx⊀x.

Linked Representation of the Queue Steps to Generate the Output


LinkedQueue Class Implementation 1. Find an item kkk with a count of direct predecessors
equal to zero (COUNT[k]==0\text{COUNT}[k] ==
Class Definition 0COUNT[k]==0) and place it in the output.
2. Scan the list of direct successors of kkk and
public class LinkedQueue<T> implements Queue<T> { decrement the count of each successor by 1.
QueueNode<T> front, rear; 3. Repeat steps 1 and 2 until all items are included in
the output.
public LinkedQueue() {
front = null; Implementation Consideration
rear = null;
} • A linked queue can be employed to efficiently track
items with a count of zero, minimizing the need to
// Additional methods for enqueue and dequeue can be repeatedly check the COUNT vector.
implemented here o Use the COUNT of each item jjj in the queue
} as a link field:
▪ COUNT[j]=k\text{COUNT}[j] =
kCOUNT[j]=k if kkk is the next item
Circular Queue in the queue.
Characteristics ▪ COUNT[j]=0\text{COUNT}[j] =
• Cells are arranged in a circular manner. 0COUNT[j]=0 if jjj is the rear
• Front points to the actual element at the front of the element in the queue.
queue.
• Rear points to the cell immediately to the right of the
actual rear element.
• Advantage: Eliminates the need to move elements to Reiterations
create space for insertion when rear = n and front > • A queue is a linearly ordered set of elements
0. following the first-in, first-out (FIFO) principle.
• Two basic queue operations:
o Insertion: at the rear.
o Deletion: at the front.
• Queues can be implemented in two ways:
o Sequential.
o Linked.
• In circular queues, no movement of elements is
needed to create room for insertion.
• The topological sorting method uses both sequential
and linked allocation techniques, with a linked queue
embedded in a sequential vector.

Application: Simulation
• Simulation: A technique where one system models
the behavior of another, often used when real-world
experimentation is too costly or hazardous.

Queuing System
• Consists of servers and queues of objects waiting for
service.
o Server: Provides the service (e.g., bank
teller, grocery cashier).
o Customer: Receives the service.
o Service Time: Duration required to serve a Binary Tree
customer (also known as transaction time). Definition
• A binary tree is a collection of nodes that is either:
o Empty, or
o Consists of:
Lesson 3: Binary Tree ▪ A root node.
Overview of Binary Trees ▪ Two binary trees:
• Definition and Related Concepts: A binary tree is a ▪ Left Subtree: A binary tree
hierarchical structure with at most two children per on the left side.
node. ▪ Right Subtree: A binary
• Properties: tree on the right side.
o Each node contains a value and references Characteristics
to its children. • The left subtree itself is a binary tree.
• The right subtree itself is also a binary tree.
Types of Binary Trees
• Various classifications based on structure and
properties.

Representation
• Can be represented using linked structures or arrays.

Binary Tree Traversals


1. Preorder
2. Inorder
3. Postorder

Understanding Graphs
• A graph G=(V,E)G = (V, E)G=(V,E) consists of:
o A finite, non-empty set of vertices VVV.
o A set of edges EEE connecting the vertices.
Binary Tree

Key Concepts
5 Examples of Graphs Definitions
• Level of a Node: The distance of the node from the
root node.
• Height (or Depth) of a Tree: The level of the
bottommost nodes; it is the length of the longest
path from the root to any leaf node.
• External Node: A node without children (leaf node);
all other nodes are considered internal.
• Proper Binary Tree: A binary tree in which each node
has either zero or two children.

Properties of a Proper Binary Tree


• Maximum Nodes at Level iii: 2i2^i2i for i≥0i \geq
0i≥0.
• Total Number of Nodes:
o At least 2k+12^k + 12k+1.
o At most 2k+1−12^{k+1} - 12k+1−1.
• Number of External Nodes:
o At least k+1k + 1k+1.
o At most 2k2^k2k.
• Number of Internal Nodes:
Notes on Graphs o At least kkk.
Key Concepts o At most 2k+1−12^{k+1} - 12k+1−1.
• Edges: The set of edges consists of pairs of adjacent
(connected) nodes. Relationship Between Nodes
• Directed vs. Undirected Graphs: • If n0n_0n0 is the number of terminal (external)
o Directed Graphs: The direction of the nodes and n2n_2n2 is the number of nodes with
connection matters. degree 2 in a binary tree, then: n0=n2+1n_0 = n_2 +
o Undirected Graphs: The connections have 1n0=n2+1
no specific direction.
• Trees:
o In a tree structure, the direction of a
connection is assumed to be “from an upper
node to a lower node,” meaning from a
parent node to a child node.
Types of Binary Trees

• Right (Left) Skewed Binary Tree: A tree in which Complete Binary Tree
every node has no left (right) subtrees, resulting in a • Definition: A complete binary tree is formed when
tree with the greatest depth. zero or more nodes are deleted from a full binary
tree in reverse-level order.
o This means that all levels of the tree are
fully filled except possibly for the last level,
which is filled from left to right.

Strictly Binary Tree


• Definition: A strictly binary tree is a tree in which
every node has either:
o Two subtrees (both left and right), or
o No subtrees at all (leaf node).
Binary Tree Structure

Reading Data Stored in a Binary Tree

Pre-Order Traversal
Full Binary Tree Steps for Pre-Order Traversal:
• Definition: A full binary tree is a strictly binary tree 1. Base Case: If the binary tree is empty, do nothing
where: (the traversal is complete).
o All terminal (external) nodes lie at the 2. Visit the Root: Process the root node.
bottom-most level. 3. Traverse the Left Subtree: Perform a pre-order
o It has the maximum number of nodes for a traversal on the left subtree.
given depth. 4. Traverse the Right Subtree: Perform a pre-order
traversal on the right subtree.
}
Inorder Traversal }
Steps for Inorder Traversal:
1. Base Case: If the binary tree is empty, do nothing
(the traversal is complete). 2. Tree Class
2. Traverse the Left Subtree: Perform an inorder • Description: A template for a binary tree (BST) that
traversal on the left subtree. involves instances of TreeNode.
3. Visit the Root: Process the root node.
4. Traverse the Right Subtree: Perform an inorder public class Tree<T> {
traversal on the right subtree. private TreeNode<T> root;

public Tree() {
this.root = null;
}

public void insert(T data) {


root = insertRec(root, data);
}

private TreeNode<T> insertRec(TreeNode<T> root, T data) {


if (root == null) {
root = new TreeNode<>(data);
return root;
}
// Assuming T implements Comparable
if (data.compareTo(root.data) < 0) {
root.left = insertRec(root.left, data);
Post-Order Traversal
} else if (data.compareTo(root.data) > 0) {
Steps for Post-Order Traversal:
root.right = insertRec(root.right, data);
1. Base Case: If the binary tree is empty, do nothing
}
(the traversal is complete).
return root;
2. Traverse the Left Subtree: Perform a post-order
}
traversal on the left subtree.
3. Traverse the Right Subtree: Perform a post-order
// Add traversal methods and other functionalities as
traversal on the right subtree.
needed
4. Visit the Root: Process the root node.
}

3. TreeTest Class
• Description: A main class that involves an instance of
the Tree class.

public class TreeTest {


public static void main(String[] args) {
Tree<Integer> tree = new Tree<>();
tree.insert(10);
tree.insert(5);
tree.insert(15);

// Call traversal methods to display the tree


}
}

Sample Codes for Binary Tree


Components of a Binary Tree Program
A binary tree program typically consists of:
• Node Template: TreeNode class.
• Tree Template: Tree class.
• Main Class: TreeTest class.

Classes
1. TreeNode Class
• Description: A template for a node in a binary tree
(Binary Search Tree).

public class TreeNode<T> {


T data;
TreeNode<T> left;
TreeNode<T> right;

public TreeNode(T data) {


this.data = data;
this.left = null;
this.right = null;
Sample Code for TreeNode Class and Binary Search Tree Binary Search Tree (BST)
(BST) • Description: A BST is a binary tree that satisfies the
BST property, meaning the value of each node is
TreeNode Class greater than the values in its left subtree and less
• Description: A template for a node in a binary tree, than those in its right subtree.
which contains references to its left and right
children and the data it stores. Properties of a Binary Search Tree:
• Each node contains:
public class TreeNode<T> { o Data value (of type T).
private TreeNode<T> leftNode; // Reference to the left child o References to its left child (which contains
private T data; // Data stored in the node smaller values).
private TreeNode<T> rightNode; // Reference to the right o References to its right child (which contains
child larger values).

/**
* Constructor to initialize the node with given data,
* and set left and right children to null.
*/
public TreeNode(T data) {
this.data = data; // Fix constructor to set instance variable
leftNode = null;
rightNode = null;
}

/**
* Setter method for the leftNode field.
*/
public void setLeft(TreeNode<T> left) { BST Operations and AVL Trees
leftNode = left; Link Representation of BST
} • In a Binary Search Tree (BST):
o If the BST is empty, the left and right
/** pointers of bstHead point to itself.
* Setter method for the rightNode field. o Otherwise, the right pointer points to the
*/ root of the tree.
public void setRight(TreeNode<T> right) {
rightNode = right;
}
BST Operations
/** Searching for a Key
* Setter method for the data field. When searching for a value kkk in a BST, three conditions are
*/ possible:
public void setData(T d) { • Successful Search: kkk equals the value at the
data = d; current node.
} • Search Left Subtree: If k<k <k< value at the current
node.
/**
• Search Right Subtree: If k>k >k> value at the current
* Getter method for the leftNode field.
node.
*/
public TreeNode<T> getLeftNode() {
Deletion of an Existing Key
return leftNode;
When deleting a key from a BST, the BST property must be
}
maintained. There are two main cases for deletion:
/**
Case 1: Node ddd is an External Node (Leaf)
* Getter method for the rightNode field.
• Action: Update the child pointer of the parent ppp:
*/
o If ddd is a left child, set p.left=nullp.left =
public TreeNode<T> getRightNode() {
nullp.left=null.
return rightNode;
o If ddd is a right child, set p.right=nullp.right
}
= nullp.right=null.
/**
Case 2: Node ddd is Internal
* Getter method for the data field.
• The deletion process for an internal node is more
*/
complex and involves restructuring the tree to
public T getData() {
maintain the BST properties.
return data;
}

/**
Time Complexity of BST Operations
* Returns a string representation of the data.
• Average Case: O(log⁡2n)O(\log_2 n)O(log2n) for
*/
search operations.
public String toString() {
• Worst Case: O(n)O(n)O(n) when the tree becomes
return data.toString();
unbalanced (e.g., resembling a linked list).
}
}
Balanced Binary Search Trees 2. Update the Balance Factor: Starting from the newly
inserted node, propagate the height increase
Importance of Balancing message up the tree to the root:
To ensure that searching takes O(log⁡2n)O(\log_2 n)O(log2n), o If the message comes from the left subtree,
balance must be maintained in a BST. increment the balance by +1.
o If it comes from the right subtree,
Balance of a Node decrement the balance by -1.
• Defined as the height of the left subtree minus the
height of the right subtree. 3. Check Balance Factor: If the resulting balance factor
becomes +2 or -2, perform the appropriate rotation
(as described above).

AVL TREES

Summary of Balanced Binary Search Trees


• A Binary Search Tree (BST) satisfies the BST
property: for any node, all values in the left subtree
are less and all values in the right subtree are
greater.

• Operations on BSTs include:


o Insertion of a new key.
o Deletion of an existing key.
o Searching for a key.
NOT AVL TREES
• The average time complexity for search operations in
a BST is O(log⁡2n)O(\log_2 n)O(log2n), while the
worst-case time complexity can reach O(n)O(n)O(n).

• Balanced BSTs (such as AVL Trees) ensure that


searching consistently takes O(log⁡2n)O(\log_2
n)O(log2n).

• An AVL Tree is a height-balanced tree where the


height difference between the left and right subtrees
of any node is at most 1.

• Rotations are crucial during insertions and deletions


to maintain the AVL Tree's balance.
Balanced Binary Search Trees (AVL Trees)
AVL Tree Rotations
In AVL Trees, rotations are used to maintain balance after Lesson 4: Tree Data Structures
insertions or deletions. Here are the four types of rotations: Overview of Tree Structures
• A Tree is a hierarchical structure consisting of nodes,
1. Simple Right Rotation (RR) where:
• Used When: The new item CCC is in the left subtree o There is a unique starting node called the
of the left child BBB of the nearest ancestor AAA root.
with a balance factor of +2. o Each node may have multiple child nodes.
o There is a unique path from the root to
2. Simple Left Rotation (LR) every other node.
• Used When: The new item CCC is in the right subtree Properties of Trees
of the right child BBB of the nearest ancestor AAA • Root Node: The top node of the tree with no parent.
with a balance factor of -2. • Child Nodes: Nodes that are connected to a parent
node.
3. Left-Right Rotation (LRR) • Unique Path: There exists a single path from the root
• Used When: The new item CCC is in the right subtree to any other node.
of the left child BBB of the nearest ancestor AAA
with a balance factor of +2.

4. Right-Left Rotation (RLR) Tree Structures and Traversals


• Used When: The new item CCC is in the left subtree Binary Tree
of the right child BBB of the nearest ancestor AAA • Definition: A Binary Tree is a tree in which each node
with a balance factor of -2. has at most two child nodes, known as the left child
and the right child.
• Leaf Node: A leaf is a node that has no children.
• Descendant: A descendant of a node is the child of
Insertion in an AVL Tree that node or a child of any of its descendants.
The insertion process in an AVL Tree is similar to that in a • Ancestor: An ancestor of a node is the parent of that
regular Binary Search Tree (BST), but the balance must be node or a parent of any of its ancestors.
checked after each insertion:

1. Insert the Leaf Node: When a new node is inserted,


it initially has a balance factor of 0.
Traversal Algorithms 3. The right child of the former left child becomes the
Depth-First Search (DFS) new left child of the former root.
• Procedure:
o Start with the root node.
o Visit all nodes of one branch as deep as
possible. Complex Rotations
o Backtrack and visit all other branches in a
similar fashion. Right-Left Rotation
• If the imbalance is caused by a long path in the left
Breadth-First Search (BFS) subtree of the right child, perform:
• Procedure: 1. A right rotation around the offending subtree.
o Start from the root node. 2. A left rotation around the root.
o Visit all nodes at the current depth before
moving to the next depth. Left-Right Rotation
o Traverses the tree “level by level.” • If the imbalance is caused by a long path in the right
subtree of the left child, perform:
1. A left rotation of the offending subtree.
2. A right rotation around the root.
Types of Binary Trees

Full Binary Tree


• A tree in which all leaves are on the same level, and Heaps
every non-leaf node has two children. Definition
• A heap is a complete binary tree where every
Complete Binary Tree element is greater than or equal to the elements of
• A binary tree that is either full or full through the both of its children (Max-Heap).
next-to-last level, with leaves on the last level being Complete Binary Tree
leftmost. • A balanced tree where all leaves are as far left as
possible. If the last level is not complete, the missing
Binary Search Tree (BST) nodes are towards the right.
• Definition: A BST is a binary tree in which the value
stored in any node is:
o Greater than or equal to the value stored in
the node’s left child. Adding a Node in a Max-Heap
o Less than the value stored in the node’s 1. Add the node as a new leaf to keep the tree
right child. complete.
2. Move the node up towards the root, exchanging
• Lexicographical Ordering: The greater than/less than positions with its parent until the Max-Heap property
relationship applies to strings as well. is restored.

Removing a Node from a Max-Heap


1. Delete the root node (the largest element).
BST Properties 2. Replace it with the last leaf of the tree.
• Each node's value is "greater than or equal" to its left 3. Move it down the tree as needed, comparing it to its
child and "less than" its right child. children, until the Max-Heap property is restored.

Balanced Binary Search Trees Min-Heap


• A Min-Heap is a heap in which each element is less
Efficiency than or equal to the elements in its children.
• Search and add operations on a balanced tree with
nnn nodes have an efficiency of O(log⁡2n)O(\log_2 Properties
n)O(log2n). • A heap is a complete binary tree.
• A degenerate tree (linear list) has search and add • Missing nodes at the last level are towards the right.
operations approaching O(n)O(n)O(n). • All nodes satisfy the heap property: the node value is
at most as large as the values of its descendants.
Balancing a Tree
• A binary tree must be balanced to ensure that search
or add operations happen in O(log⁡n)O(\log
n)O(logn).
• Rotations are performed on a binary search tree to
maintain balance.

Left Rotation
1. Make the right child of the root the new root.
2. The former root becomes the left child of the new
root.
3. The left child of the former right child becomes the
new right child of the former root.

Right Rotation
1. Make the left child of the root the new root.
2. The former root becomes the right child of the new
root.

You might also like