VOOZH about

URL: https://www.geeksforgeeks.org/dsa/avl-tree-implementation-in-golang/

⇱ AVL Tree Implementation in Golang - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

AVL Tree Implementation in Golang

Last Updated : 28 Apr, 2025

An AVL tree is a type of self-balancing binary search tree that maintains the balance of the tree by ensuring that the difference between the heights of the left and right subtrees is at most one. This allows for efficient insertion, deletion, and search operations.

Approach:

We start by defining a node structure that will store the data, the left and right pointers to the children nodes, and the balance factor.

type Node struct {
key  int
left *Node
right *Node
height int
}

Steps Involved in Implementation:

  • Insertion: We start by inserting the node at the correct position in the tree. We then traverse up the tree and check the balance factor at each node. If the balance factor of any node is found to be greater than 1 or less than -1, then we need to perform a rotation to restore the balance of the tree.
  • Deletion: The deletion process is similar to insertion except that we need to check the balance factor at each node after the node is deleted. We also need to perform a rotation if the balance factor of any node is found to be greater than 1 or less than -1.
  • Search: The search process is similar to that of a regular binary search tree. We start at the root node and compare the data to be searched with the current node’s data. If the data is found, we return the node. If the data is less than the current node’s data, we move to the left child. If the data is greater than the current node’s data, we move to the right child. We keep repeating the process until the data is found or we reach a leaf node.

Below is the implementation of AVL Tree in Golang:

Output:

R----33
 L----13
 | L----9
 | | L----8
 | | R----11
 | R----21
 R----53
 R----61
After deleting 
R----33
 L----9
 | L----8
 | R----21
 | L----11
 R----53
 R----61

Time Complexity: O(log n)
Auxiliary Space: O(n)

Comment
Article Tags: