I have an theoretical question about Balanced BST
.
I would like to build Perfect Balanced Tree
that has 2^k - 1
nodes, from a regular unbalanced BST
. The easiest solution I can think of is to use a sorted Array/Linked list
and recursively divide the array to sub-arrays, and build Perfect Balanced BST
from it.
However, in a case of extremely large Tree sizes, I will need to create an Array/List
in the same size so this method will consume a large amount of memory.
Another option is to use AVL
rotation functions, inserting element by element and balancing the tree with rotations depending on the Tree Balance Factor - three height of the left and right sub trees.
My questions are, am I right about my assumptions? Is there any other way to create a perfect BST
from unbalanced BST
?
AVL and similar trees are not perfectly balanced so I'm not sure how they are useful in this context.
You can build a doubly-linked list out of tree nodes, using left
and right
pointers in lieu of forward
and backward
pointers. Sort that list, and build the tree recursively from the bottom up, consuming the list from left to right.
Building a tree of size 1 is trivial: just bite the leftmost node off the list.
Now if you can build a tree of size N
, you can also build a tree of size 2N+1
: build a tree of size N
, then bite off a single node, then build another tree of size N
. The singe node will be the root of your larger tree, and the two smaller trees will be its left and right subtrees. Since the list is sorted, the tree is automatically a valid search tree.
This is easy to modify for sizes other than 2^k-1
too.
Update: since you are starting from a search tree, you can build a sorted list directly from it in O(N)
time and O(log N)
space (perhaps even in O(1)
space with a little ingenuity), and build the tree bottom-up also in O(N)
time and O(log N)
(or O(1)
) space.
I did not yet find a very good situation for needing a perfectly balanced search tree. If your case really needs it, I would like to hear about it. Usually it is better and faster to have a almost balanced tree.
If you have a large search tree, throwing away all existing structure is usually no good idea. Using rotation functions is a good way of getting a more balanced tree while preserving most of the existing structure. But normally you use a suitable data structure to make sure you never have a completely unbalanced tree. So called self balancing trees.
There is for example an AVL tree, a red-black-tree or a splay-tree, which use slightly different variants of rotation to keep the tree balanced.
If you really have a totally unbalanced tree you might have a different problem. - In your case rotating it the AVL way is probably the best way to fix it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With