frog
frog

Reputation: 31

BST tree to AVL

i was wondering how can i convert a BST to an avl in O(nlogn) time if every node of the BST is:

struct node{
    int leftHeight;
    int rightHeight;
    struct node* lr;
    struct node* rc;
}

Do i have to visit every node of the bst to check if the balance is different than 0,1, -1? And if so i have to check if it's a right or left child so that i will perform left or right rotation respectively? How do i do that?

I'm using C. Please don't judge me i'm a beginner.

Upvotes: 0

Views: 2042

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

So you have a Binary Search Tree and you want to convert that to a balanced search tree (AVL tree) and wonder if that can be done in O(n.log(n)).

After giving it a quick study, the general approach is to keep the tree balanced while building it. The other approach is to create a new tree that is balanced (using the AVL algorithm).

To balance a tree in-place you can use the Stout-Warren algorithm, the reference I found in another Stack Overflow question, Balancing a binary search tree.

The article quoted states its procedure works in linear time, that is O(n) which is less than O(n.log(n)).

Upvotes: 1

Related Questions