Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an AVL Tree from ArrayList of values in O(n) time?

Tags:

algorithm

tree

My assignment is to create an AVL Tree from a sorted array list of values in O(n) time where n is the number of values

I have been working on this but I cannot get O(n) time, the best I can get is O(nlog(n))

My problem is that every time a node that causes the tree to be unbalanced is inserted, I have to do another loop to find the node that is unbalanced and apply rotation(s) to balance the tree again.

Any help is greatly appreciated, thanks!

like image 571
Danny Avatar asked Oct 24 '10 22:10

Danny


People also ask

What is the time complexity of height of an AVL tree?

The AVL tree is a self-balancing binary search tree, so the tree's height in the worst case goes O(logN). The AVL tree's guaranteed height h is O(logN). Balancing the tree rotations is necessary, and it takes O(1) time. So overall complexity in the worst case remains O(logN).

Can you create AVL tree without performing rotation?

The answer is... yes and no. B-trees don't need to perform rotations because they have some slack with how many different keys they can pack into a node. As you add more and more keys into a B-tree, you can avoid the tree becoming lopsided by absorbing those keys into the nodes themselves.

Why are AVL trees log n?

AVL trees require the heights of the subtrees of any node to differ by no more than one level, which ensures that the height is O(log N).

What is the formula for AVL tree?

If height of AVL tree is h, maximum number of nodes can be 2h+1 – 1. Minimum number of nodes in a tree with height h can be represented as: N(h) = N(h-1) + N(h-2) + 1 for n>2 where N(0) = 1 and N(1) = 2. The complexity of searching, inserting and deletion in AVL tree is O(log n).


1 Answers

How about just creating a complete balanced tree, with a few nodes at the lowest level possibly missing, e.g., for 6 elements, create

      o
    /   \
   o     o
  / \    /
 o   o  o

Then do an inorder walk, and when you visit the i-th node, set its key to A[i].

This is a valid AVL tree, since every node has a left and right child whose heights differ by at most one.

The original tree can be constructed in O(n), and the inorder walk in O(n), so the complexity is O(n).

Incidentally, on a semirelated note, there's a technique called heapify for building a heap (mix or max) out of an array of integers that's O(n) for a length n array, even though the insertion into a heap is O(log n) - the trick is to do it bottom up.

like image 154
user486972 Avatar answered Nov 15 '22 07:11

user486972