Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Different shapes of AVL possible at height h
Next article icon

Optimal sequence for AVL tree insertion (without any rotations)

Last Updated : 06 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of integers, the task is to find the sequence in which these integers should be added to an AVL tree such that no rotations are required to balance the tree.

Examples : 

Input : array = {1, 2, 3} Output : 2 1 3  Input : array = {2, 4, 1, 3, 5, 6, 7} Output : 4 2 6 1 3 5 7

Approach : 

  • Sort the given array of integers.
  • Create the AVL tree from the sorted array by following the approach described here.
  • Now, find the level order traversal of the tree which is the required sequence.
  • Adding numbers in the sequence found in the previous step will always maintain the height balance property of all the nodes in the tree.

Below is the implementation of the above approach : 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
/* A Binary Tree node */
struct TNode {
    int data;
    struct TNode* left;
    struct TNode* right;
};
 
struct TNode* newNode(int data);
 
/* Function to construct AVL tree
   from a sorted array */
struct TNode* sortedArrayToBST(vector<int> arr, int start, int end)
{
    /* Base Case */
    if (start > end)
        return NULL;
 
    /* Get the middle element
       and make it root */
    int mid = (start + end) / 2;
    struct TNode* root = newNode(arr[mid]);
 
    /* Recursively construct the
       left subtree and make it
       left child of root */
    root->left = sortedArrayToBST(arr, start, mid - 1);
 
    /* Recursively construct the
       right subtree and make it
       right child of root */
    root->right = sortedArrayToBST(arr, mid + 1, end);
 
    return root;
}
 
/* Helper function that allocates
   a new node with the given data
   and NULL to the left and
   the right pointers. */
struct TNode* newNode(int data)
{
    struct TNode* node = new TNode();
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return node;
}
 
// This function is used for testing purpose
void printLevelOrder(TNode *root)
{
    if (root == NULL)  return;
 
    queue<TNode *> q;
    q.push(root);
   
    while (q.empty() == false)
    {
        TNode *node = q.front();
        cout << node->data << " ";
        q.pop();
        if (node->left != NULL)
            q.push(node->left);
        if (node->right != NULL)
            q.push(node->right);
    }
}  
 
/* Driver program to
test above functions */
int main()
{
 
    // Assuming the array is sorted
    vector<int> arr = { 1, 2, 3, 4, 5, 6, 7 };
    int n = arr.size();
 
    /* Convert List to AVL tree */
    struct TNode* root = sortedArrayToBST(arr, 0, n - 1);
    printLevelOrder(root);
 
    return 0;
}
 
 

Java




   
// Java implementation of the approach
import java.util.*;
class solution
{
 
/* A Binary Tree node */
 static  class TNode {
    int data;
     TNode left;
     TNode right;
}
 
 
/* Function to con AVL tree
   from a sorted array */
 static TNode sortedArrayToBST(int arr[], int start, int end)
{
    /* Base Case */
    if (start > end)
        return null;
 
    /* Get the middle element
       and make it root */
    int mid = (start + end) / 2;
     TNode root = newNode(arr[mid]);
 
    /* Recursively construct the
       left subtree and make it
       left child of root */
    root.left = sortedArrayToBST(arr, start, mid - 1);
 
    /* Recursively construct the
       right subtree and make it
       right child of root */
    root.right = sortedArrayToBST(arr, mid + 1, end);
 
    return root;
}
 
/* Helper function that allocates
   a new node with the given data
   and null to the left and
   the right pointers. */
static  TNode newNode(int data)
{
     TNode node = new TNode();
    node.data = data;
    node.left = null;
    node.right = null;
 
    return node;
}
 
// This function is used for testing purpose
static void printLevelOrder(TNode root)
{
    if (root == null)  return;
 
    Queue<TNode > q= new LinkedList<TNode>();
    q.add(root);
   
    while (q.size()>0)
    {
        TNode node = q.element();
        System.out.print( node.data + " ");
        q.remove();
        if (node.left != null)
            q.add(node.left);
        if (node.right != null)
            q.add(node.right);
    }
}  
 
/* Driver program to
test above functions */
public static void main(String args[])
{
 
    // Assuming the array is sorted
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = arr.length;
 
    /* Convert List to AVL tree */
     TNode root = sortedArrayToBST(arr, 0, n - 1);
    printLevelOrder(root);
 
}
}
//contributed by Arnab Kundu
 
 

Python3




# Python3 code to print order of
# insertion into AVL tree to
# ensure no rotations
 
# Tree Node
class Node:
    def __init__(self, d):
        self.data = d
        self.left = None
        self.right = None
 
# Function to convert sorted array
# to a balanced AVL Tree/BST
# Input : sorted array of integers
# Output: root node of balanced AVL Tree/BST
def sortedArrayToBST(arr):
     
    if not arr:
        return None
 
    # Find middle and get its floor value
    mid = int((len(arr)) / 2)
    root = Node(arr[mid])
     
    # Recursively construct the left
    # and right subtree
    root.left = sortedArrayToBST(arr[:mid])
    root.right = sortedArrayToBST(arr[mid + 1:])
 
    # Return the root of the
    # constructed tree
    return root
 
# A utility function to print the
# Level Order Traversal of AVL Tree
# using a Queue
def printLevelOrder(root):
    if not root:
        return
     
    q = []
    q.append(root)
 
    # Keep printing the top element and
    # adding to queue while it is not empty
    while q != []:
        node = q.pop(0)
        print(node.data, end=" ")
 
        # If left node exists, enqueue it
        if node.left:
            q.append(node.left)
 
        # If right node exists, enqueue it
        if node.right:
            q.append(node.right)
 
# Driver Code
arr = [1, 2, 3, 4, 5, 6, 7]
root = sortedArrayToBST(arr)
printLevelOrder(root)
 
# This code is contributed
# by Adikar Bharath
 
 

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
/* A Binary Tree node */
public class TNode
{
    public int data;
    public TNode left;
    public TNode right;
}
 
 
/* Function to con AVL tree
from a sorted array */
static TNode sortedArrayToBST(int []arr,
                    int start, int end)
{
    /* Base Case */
    if (start > end)
        return null;
 
    /* Get the middle element
    and make it root */
    int mid = (start + end) / 2;
    TNode root = newNode(arr[mid]);
 
    /* Recursively construct the
    left subtree and make it
    left child of root */
    root.left = sortedArrayToBST(arr, start, mid - 1);
 
    /* Recursively construct  the
    right subtree and make it
    right child of root */
    root.right = sortedArrayToBST(arr, mid + 1, end);
 
    return root;
}
 
/* Helper function that allocates
a new node with the given data
and null to the left and
the right pointers. */
static TNode newNode(int data)
{
    TNode node = new TNode();
    node.data = data;
    node.left = null;
    node.right = null;
 
    return node;
}
 
// This function is used for testing purpose
static void printLevelOrder(TNode root)
{
    if (root == null) return;
 
    Queue<TNode > q = new Queue<TNode>();
    q.Enqueue(root);
     
    while (q.Count > 0)
    {
        TNode node = q.Peek();
        Console.Write( node.data + " ");
        q.Dequeue();
        if (node.left != null)
            q.Enqueue(node.left);
        if (node.right != null)
            q.Enqueue(node.right);
    }
}
 
/* Driver code */
public static void Main()
{
 
    // Assuming the array is sorted
    int []arr = { 1, 2, 3, 4, 5, 6, 7 };
    int n = arr.Length;
 
    /* Convert List to AVL tree */
    TNode root = sortedArrayToBST(arr, 0, n - 1);
    printLevelOrder(root);
}
}
 
/* This code contributed by PrinciRaj1992 */
 
 

Javascript




<script>
 
// Javascript implementation of the approach
 
/* A Binary Tree node */
class TNode
{
    constructor()
    {
        this.data = 0;
        this.left = null;
        this.right = null;
    }
}
 
 
/* Function to con AVL tree
from a sorted array */
function sortedArrayToBST(arr, start, end)
{
    /* Base Case */
    if (start > end)
        return null;
 
    /* Get the middle element
    and make it root */
    var mid = parseInt((start + end) / 2);
    var root = newNode(arr[mid]);
 
    /* Recursively construct the
    left subtree and make it
    left child of root */
    root.left = sortedArrayToBST(arr, start, mid - 1);
 
    /* Recursively construct the
    right subtree and make it
    right child of root */
    root.right = sortedArrayToBST(arr, mid + 1, end);
 
    return root;
}
 
/* Helper function that allocates
a new node with the given data
and null to the left and
the right pointers. */
function newNode(data)
{
    var node = new TNode();
    node.data = data;
    node.left = null;
    node.right = null;
 
    return node;
}
 
// This function is used for testing purpose
function printLevelOrder(root)
{
    if (root == null) return;
 
    var q = [];
    q.push(root);
     
    while (q.length > 0)
    {
        var node = q[0];
        document.write( node.data + " ");
        q.shift();
        if (node.left != null)
            q.push(node.left);
        if (node.right != null)
            q.push(node.right);
    }
}
 
/* Driver code */
// Assuming the array is sorted
var arr = [1, 2, 3, 4, 5, 6, 7];
var n = arr.length;
 
/* Convert List to AVL tree */
var root = sortedArrayToBST(arr, 0, n - 1);
printLevelOrder(root);
 
// This code is contributed by itsok.
 
</script>
 
 
Output
4 2 6 1 3 5 7 

Complexity Analysis:

  • Time Complexity: O(N)
  • Auxiliary Space: O(N) 


Next Article
Different shapes of AVL possible at height h

K

krikti
Improve
Article Tags :
  • Advanced Data Structure
  • Algorithms
  • Binary Search Tree
  • DSA
  • AVL-Tree
Practice Tags :
  • Advanced Data Structure
  • Algorithms
  • AVL-Tree
  • Binary Search Tree

Similar Reads

  • AVL Tree Data Structure
    An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
    4 min read
  • What is AVL Tree | AVL Tree meaning
    An AVL is a self-balancing Binary Search Tree (BST) where the difference between the heights of left and right subtrees of any node cannot be more than one. KEY POINTSIt is height balanced treeIt is a binary search treeIt is a binary tree in which the height difference between the left subtree and r
    2 min read
  • Insertion in an AVL Tree
    AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. Example of AVL Tree: The above tree is AVL because the differences between the heights of left and right subtrees for every node are less than
    15+ min read
  • Insertion, Searching and Deletion in AVL trees containing a parent node pointer
    AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. The insertion and deletion in AVL trees have been discussed in the previous article. In this article, insert, search, and delete operations are
    15+ min read
  • Deletion in an AVL Tree
    We have discussed AVL insertion in the previous post. In this post, we will follow a similar approach for deletion. Steps to follow for deletion. To make sure that the given tree remains AVL after every deletion, we must augment the standard BST delete operation to perform some re-balancing. Followi
    15+ min read
  • How is an AVL tree different from a B-tree?
    AVL Trees: AVL tree is a self-balancing binary search tree in which each node maintain an extra factor which is called balance factor whose value is either -1, 0 or 1. B-Tree: A B-tree is a self - balancing tree data structure that keeps data sorted and allows searches, insertions, and deletions in
    1 min read
  • Practice questions on Height balanced/AVL Tree
    AVL tree is binary search tree with additional property that difference between height of left sub-tree and right sub-tree of any node can’t be more than 1. Here are some key points about AVL trees: If there are n nodes in AVL tree, minimum height of AVL tree is floor(log 2 n). If there are n nodes
    4 min read
  • AVL with duplicate keys
    Please refer below post before reading about AVL tree handling of duplicates. How to handle duplicates in Binary Search Tree?This is to augment AVL tree node to store count together with regular fields like key, left and right pointers. Insertion of keys 12, 10, 20, 9, 11, 10, 12, 12 in an empty Bin
    15+ min read
  • Count greater nodes in AVL tree
    In this article we will see that how to calculate number of elements which are greater than given value in AVL tree. Examples: Input : x = 5 Root of below AVL tree 9 / \ 1 10 / \ \ 0 5 11 / / \ -1 2 6 Output : 4 Explanation: there are 4 values which are greater than 5 in AVL tree which are 6, 9, 10
    15+ min read
  • Difference between Binary Search Tree and AVL Tree
    Binary Search Tree:A binary Search Tree is a node-based binary tree data structure that has the following properties: The left subtree of a node contains only nodes with keys lesser than the node’s key.The right subtree of a node contains only nodes with keys greater than the node’s key.The left and
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences