Back to Data Structures & Algorithms
2026-01-066 min read

Algorithm to Insert a newNode (Data Structures & Algorithms)

Learn Algorithm to Insert a newNode (Data Structures & Algorithms) step by step with clear examples and exercises.

Title: Algorithm to Insert a New Node (Data Structures & Algorithms)

Why This Matters

In programming, inserting a new node into a data structure like a linked list or a binary tree is a fundamental operation that comes up frequently during the development of applications and algorithms. Understanding this concept can help you tackle real-world problems more effectively, prepare for interviews, and even debug issues in your code.

Prerequisites

To fully grasp the algorithm to insert a new node, it's essential to have a good understanding of the following concepts:

  1. Basic Python syntax
  2. Data structures such as lists and dictionaries
  3. Linked lists (singly and doubly linked lists)
  4. Binary trees (specifically binary search trees like AVL trees)
  5. Recursion
  6. Understanding of memory allocation in Python

Core Concept

Inserting a New Node in a Singly Linked List

A singly linked list consists of nodes where each node contains data and a reference to the next node. To insert a new node, we need to:

  1. Allocate memory for the new node.
  2. Assign the data to the new node.
  3. Link the new node to the appropriate position in the linked list (either at the beginning or after an existing node).
  4. Update the next pointer of the previous node to point to the newly inserted node.

Here's a simple example:

class Node:
def __init__(self, data):
self.data = data
self.next = None

def insert_at_beginning(head, data):
new_node = Node(data)
new_node.next = head
return new_node

def insert_after_node(prev_node, data):
if prev_node is None:
print("The previous node cannot be None.")
return

new_node = Node(data)
new_node.next = prev_node.next
prev_node.next = new_node

def print_list(head):
current = head
while current is not None:
print(current.data, end=" -> ")
current = current.next
print("None")

Initialize a linked list

head = Node(1)

head.next = Node(2)

head.next.next = Node(3)

head.next.next.next = Node(4)

print("Original Linked List:")

print_list(head)

insert_at_beginning(head, 0)

print("\nLinked List after inserting at the beginning:")

print_list(head)

insert_after_node(head.next, 5)

print("\nLinked List after inserting after node 2:")

print_list(head)


### Inserting a New Node in a Binary Search Tree (AVL Tree)

An AVL tree is a self-balancing binary search tree that maintains the height of both subtrees and rebalances itself after each insertion, deletion, or rotation to ensure the height difference between the two subtrees doesn't exceed 1.

To insert a new node in an AVL tree:

1. Perform a binary search to find the appropriate position for the new node.
2. Insert the new node as a leaf node.
3. If the insertion violates the AVL property (height difference between the two subtrees exceeds 1), perform necessary rotations and rebalancing operations to restore the balance.

Here's an example of inserting a new node in an AVL tree:

class Node:

def __init__(self, key):

self.key = key

self.height = 1

self.left = None

self.right = None

def height(node):

if node is None:

return 0

return node.height

def get_balance_factor(node):

if node is None:

return 0

return height(node.left) - height(node.right)

def rotate_right(root):

y = root.left

T2 = y.right

y.right = root

root.left = T2

root.height = max(height(root.left), height(root.right)) + 1

y.height = max(height(y.left), height(y.right)) + 1

return y

def rotate_left(root):

y = root.right

T2 = y.left

y.left = root

root.right = T2

root.height = max(height(root.left), height(root.right)) + 1

y.height = max(height(y.left), height(y.right)) + 1

return y

def rebalance_AVL(node):

if node is None:

return None

balance = get_balance_factor(node)

if balance > 1 and get_balance_factor(node.left) >= 0:

node = rotate_right(node)

elif balance > 1 and get_balance_factor(node.left) < 0:

node.left = rotate_left(node.left)

node = rotate_right(node)

elif balance < -1 and get_balance_factor(node.right) <= 0:

node = rotate_left(node)

elif balance < -1 and get_balance_factor(node.right) > 0:

node.right = rotate_right(node.right)

node = rotate_left(node)

node.height = max(height(node.left), height(node.right)) + 1

return node

def insert(root, key):

if root is None:

return Node(key)

if root.key < key:

root.right = insert(root.right, key)

root = rebalance_AVL(root)

else:

root.left = insert(root.left, key)

root = rebalance_AVL(root)

return root

def inorder_traversal(root):

if root is None:

return

inorder_traversal(root.left)

print(root.key, end=" -> ")

inorder_traversal(root.right)

Initialize an empty AVL tree

root = None

keys = [10, 20, 30, 40, 50]

for key in keys:

root = insert(root, key)

print("Inorder traversal of the constructed AVL tree:")

inorder_traversal(root)

Worked Example

Let's work through an example to better understand how to insert a new node in a binary search tree (AVL tree). We will insert the key 15 into the following AVL tree:

20
/ \
15 30
/ \
10 40
  1. Perform a binary search to find the appropriate position for the new node (key 15). Since 15 is between 10 and 20, we will insert it as the right child of 10.
20
/ \
15 30
/ \
10 40
\
15
  1. Insert the new node (key 15) as a leaf node.
20
/ \
15 30
/ \
10 40
\
15
  1. Check if the insertion violates the AVL property (height difference between the two subtrees exceeds 1). In this case, it does not.

Common Mistakes

Forgetting to update the height of the node after inserting a new child

Ensure that you always update the height of the current node whenever a new child is inserted or an existing child is deleted. This is crucial for maintaining the balance in AVL trees and other self-balancing binary search trees.

Ignoring the need to rebalance the tree after inserting a new node

After inserting a new node, always check if the height difference between the two subtrees exceeds 1. If it does, perform necessary rotations and rebalancing operations to restore the balance.

Practice Questions

  1. Implement a function to delete a node in an AVL tree.
  2. Write a Python program to implement a doubly linked list.
  3. Given a singly linked list, write a function to find the middle of the list.
  4. Implement a binary search algorithm for a sorted array in Python.
  5. Write a Python program to perform depth-first search (DFS) on an undirected graph.

FAQ

Q: What is the time complexity of inserting a new node in a singly linked list?

A: The time complexity for inserting a new node in a singly linked list is O(1), assuming that we have constant-time access to memory.

Q: How does the height of a node get updated when a new child is inserted or an existing child is deleted in an AVL tree?

A: The height of a node gets updated by recursively calculating the maximum height of its left and right subtrees, then adding 1 to the result.

Q: What are some common self-balancing binary search trees apart from AVL trees?

A: Some other popular self-balancing binary search trees include Red-Black Trees, Splay Trees, and Treap (a randomized binary search tree).

Q: Why do we need to rebalance the AVL tree after inserting a new node or performing rotations?

A: Rebalancing is necessary to maintain the height difference between the two subtrees of each node within a specific range (1 in the case of AVL trees), which ensures that the tree remains balanced and the operations like search, insert, delete, etc., can be performed efficiently.

Algorithm to Insert a newNode (Data Structures & Algorithms) | Data Structures & Algorithms | XQA Learn