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.
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)).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.