I'm trying to solve the following problem: "Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a BST with minimal height."
The given answer takes the root node to be the middle of the array. While doing this makes sense to me intuitively, I'm trying to prove, rigorously, that it's always best to make the root node the middle of the array.
The justification given in the book is: "To create a tree of minimal height, we need to match the number of nodes in the left subtree to the number of nodes in the right subtree as much as possible. This means that we want the root node to be the middle of the array, since this would mean that half the elements would be less than the root and half would be greater."
I'd like to ask:
Why would any tree of minimal height be one where the number of nodes in the left subtree be as equal as possible to the number of nodes in the right subtree? (Or, do you have any other way to prove that it's best to make the root node the middle of the array?)
Is a tree with minimal height the same as a tree that's balanced? From a previous question on SO, that's the impression I got, (Visualizing a balanced tree) but I'm confused because the book specifically states "BST with minimal height" and never "balanced BST".
Thanks.
Source: Cracking the Coding Interview
The way I like to think about it, if you balance a tree using tree rotations (zig-zig and zig-zag rotations) you will eventually reach a state in which the left and right subtree differ by at most height of one. It is not always the case that a balanced tree must have the same number of children on the right and the left; however, if you have that invariant(same # of children on each side), you can reach a tree that is balanced using tree rotations)
Balance is defined arbitrarily. AVL trees define it in such as way that no subtree of the tree has a children whose heights differ by more than one. Other trees define balance in different ways, so they are not the same distinction. They are inherently related yet not exactly the same. That being said, a tree of minimal height will always be balanced under any definition since balancing exists to maintain a O(log(n)) lookup time of the BST.
If I missed anything or said anything wrong, feel free to edit/correct me.
Hope this helps
Why would any tree of minimal height be one where the number of nodes
in the left subtree be as equal as possible to the number of nodes in
the right subtree?
There can be a scenario where in minimal height tree which are ofcourse balanced can have different number of node count on left and right hand side. BST worst case traversal is O(n) in case if it is sorted and in minimal height trees the complexity for worst case is O(log n).
*
/ \
* *
/
*
Here you can clearly see that left node count and right nodes are not equal though it is a minimal height tree.
Is a tree with minimal height the same as a tree that's balanced? From a previous question on SO, that's the impression I got, (Visualizing a balanced tree) but I'm confused because the book specifically states "BST with minimal height" and never "balanced BST".
Minimal height tree is balanced one, for more details you can take a look on AVL trees which are also known as height-balanced trees. While making BST a height balanced tree you have to perform rotations (LR, RR, LL, RL).
Related
PREMISE
So lately i have been thinking of a problem that is common to databases: trying to optimize insertion, search, deletion and update of data.
Usually i have seen that most of the databases nowadays use the BTree or B+Tree to solve such a problem, but they are usually used to store data inside the disk and i wanted to work with in-memory data, so i thought about using the AVLTree (the difference should be minimal because the purpose of the BTrees is kind of the same of the AVLTree but the implementation is different and so are the effects).
Before continuing with the reasoning behind this i would like to get in a deeper level of what i am trying to solve.
So in a modern database data stored in a table with a PRIMARY KEY which tends to be INDEXED (i am not very experienced in indexing so what i will say is basic reasoning i put into this problem), usually the PRIMARY KEY is an increasing number (even though nowadays is a bad practice) starting from 1.
Using normally an AVLTree should be more then enough to solve the problem cause this particular tree is always balanced and offers O(log2(n)) operations, BUT i wanted to reach this on a deeper level trying to optimize it even more then needed.
THEORY
So as the title of the question suggests i am trying to optimize the AVLTree merging it with a Btree.
Basically every node of this new Tree is lets say an array of ten elements every node as also the corresponding height in the tree and every element of the array is ordered ascending.
INSERTION
The insertion initally fills the array of the root node when the root node is full it generates the left and right children which also contains an array of 10 elements.
Whenever a new node is added the Tree autorebalances the nodes based on the first key of the vectors of the left and right child using also their height (note that this is actually how the AVLTree behaves but the AVLTree only has 2 nodes and no vector just the values).
SEARCH
Searching an element works this way: staring from the root we compare the value we are searching K with the first and last key of the array of the current node if the value is in between, we know that it surely will be in the array of the current node so we can start using a binarySearch with O(log2(n)) complexity into this array of ten elements, otherise we go on the left if the key we are searcing is smaller then the first key or we go to the right if it is bigger.
DELETION
The same of the searching but we delete the value.
UPDATE
The same of the searching but we update the value.
CONCLUSION
If i am not wrong this should have a complexity of O(log10(log2(10))) which is always logarithmic so we shouldn't care about this optimization, but in my opinion this could make the height of the tree so much smaller while providing also quick time on the search.
B tree and B+ tree are indeed used for disk storage because of the block design. But there is no reason why they could not be used also as in-memory data structure.
The advantages of a B tree include its use of arrays inside a single node. Look-up in a limited vector of maybe 10 entries can be very fast.
Your idea of a compromise between B tree and AVL would certainly work, but be aware that:
You need to perform tree rotations like in AVL in order to keep the tree balanced. In B trees you work with redistributions, merges and splits, but no rotations.
Like with AVL, the tree will not always be perfectly balanced.
You need to describe what will be done when a vector is full and a value needs to be added to it: the node will have to split, and one half will have to be reinjected as a leaf.
You need to describe what will be done when a vector gets a very low fill-factor (due to deletions). If you leave it like that, the tree could degenerate into an AVL tree where every vector only has 1 value, and then the additional vector overhead will make it less efficient than a genuine AVL tree. To keep the fill-factor of a vector above a minimum you cannot easily apply the redistribution mechanism with a sibling node, as would be done in B-trees. It would work with leaf nodes, but not with internal nodes. So this needs to be clarified...
You need to describe what will be done when a value in a vector is updated. Of course, you would insert it in its sorted position: but if it becomes the first or last value in that vector, this may violate the order with regards to left and right children, and so also there you may need to define more precisely the algorithm.
Binary search in a vector of 10 may be overkill: a simple left-to-right scan may be faster, as CPUs are optimised to read consecutive memory. This does not impact the time complexity, since we set that the vector size is limited to 10. So we are talking about doing either at most 4 comparisons (3-4 on average depending on binary search implementation) or at most 10 comparisons (5 on average).
If I am not wrong this should have a complexity of O(log10(log2(n))) which is always logarithmic
Actually, if that were true, it would be sub-logarithmic, i.e. O(loglogn). But there is a mistake here. The binary search in a vector is not related to n, but to 10. Also, this work comes in addition to finding the node with that vector. So it is not a logarithm of a logarithm, but a sum of logarithms:
O(log10n + log210) = O(log n)
Therefore the time complexity is no different than the one for AVL or B-tree -- provided that the algorithm is completed with the missing details, keeping within the logarithmic complexity.
You should maybe also consider to implement a pure B tree or B+ tree: that way you also benefit from some of the advantages that neither the AVL, nor the in-between structure has:
The leaves of the tree are all at the same level
No rotations are needed
The tree height only changes at one spot: the root.
B+ trees provide a very fast mean for iterating all values in their order.
I need a start point to implement an algorithm in c to generate a tre-decomposition of a graph in input. What i'm looking for it's an algorithm to do this thing. i will like to have a pseudocode of the algorithm, i don't care about the programming language and I do not care about complexity
On the web there is a lot of theory but nothing in practice. I've tried to understand how to do an algorithm that can be implemented in c. But it's to hard
i've tried to use the following information:
Algorithm for generating a tree decomposition
https://math.mit.edu/~apost/courses/18.204-2016/18.204_Gerrod_Voigt_final_paper.pdf
and a lot of other info-material. But nothing of this link was useful.
can anyone help me?
So, here is the algorithm to find a node in the tree.
Select arbitrary node v
Start a DFS from v, and setup subtree sizes
Re-position to node v (or start at any arbitrary v that belongs to the tree)
Check mathematical condition of centroid for v
If condition passed, return current node as centroid
Else move to adjacent node with ‘greatest’ subtree size, and back to step 4
And the algorithm for tree decomposition
Make the centroid as the root of a new tree (which we will call as the ‘centroid tree’)
Recursively decompose the trees in the resulting forest
Make the centroids of these trees as children of the centroid which last split them.
And here is an example code.
https://www.geeksforgeeks.org/centroid-decomposition-of-tree/amp/
I was recently studying Uninformed Search from here. In the case of Depth First Search, it is given that the space taken by the fringe is O(b.m), but I am unable to figure out how(I could not find proof of this anywhere online). Any help or pointers to specific material would be much appreciated.
A depth-first tree search needs to store only a single path from the root to a leaf node, along with the remaining unexpanded sibling nodes for each node on the path.
Once a node has been expanded, it can be removed from memory as soon as all its descendants has been fully expanded.
So that, for a state space with branching factor band maximum depth m, depth-first search requires storage of only O(b*m).
ref. Russel & Norvig, Artificial Intelligence, Figure 3.16, p87
The Depth First Search (DFS) algorithm has to store few nodes in the fridge because it processes the lastly added node first (Last In First Out), which results in a space complexity of O(bd). Thus, for a depth of d it has to store at most the b children of the d nodes above.
The Breadth First Search (BFS) algorithm, however, gets the firstly inserted node first (First In First Out). Because of this, it has to keep track of all the children nodes it encounters, which results in a space complexity of O(b^d).
Thus, for a depth of d it has to store the children and the children's children, etc., resulting in the exponential growth.
I have a question regarding the insertion in an AVL Tree. I noticed that there are some cases in which for example, after you inserted an element, both the parent and it's child are breaking the AVL condition. For example here https://www.youtube.com/watch?v=EsgAUiXbOBo, at min. 12:50, when after 1 was inserted, both 4 and 3 are breaking the AVL condition. My question is on which node should we do the rotation. The closest one to the root (in this case is the root itself) or the one who is farthest from the root, as we would get two different trees in those cases? Or is it correct either way?
Rotation starts from the bottom (the inserted node).
Let's consider having balanced all nodes up to P (included). So the subtree of P is perfectly balanced. We go to P's parent (Q). The subtree of Q is checked and (eventually) rotated. The result tree (the root may have changed if a rotation was performed) is perfectly balanced. Advance up again.
Believing the wikipedia article: http://en.wikipedia.org/wiki/AVL_tree
AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced;[4] that is, sibling nodes can have hugely differing numbers of descendants.
But, as an AVL tree is:
a self-balancing binary search tree [...]. In an AVL tree, the heights of the two child subtrees of any node differ by at most one
I don't see how an AVL could be weight-unbalanced since -if I understood the definition of an AVL tree well-, every sibling will have approximately the same number of child since they have the same height +/- 1.
So, could you give me an example of an AVL tree which is unbalanced ? I did not succeed to find one. Thus, or I misunderstood the definition of an AVL/unweighted tree, or the wikipedia article is false...
Thanks
You are correct in your understanding that an AVL tree is defined by the nearly-uniform height of its edge nodes, but your confusion appears to be about the difference between node position and edge weight.
That is: In an AVL tree, the depth of the edge nodes will the same +/- (but not both!) one. This makes no claims as to the cost associated with an edge between the nodes. For an AVL tree with a root node and two children, the left path may be twice as expensive to traverse as the right path. This would make the tree weight-unbalanced, but still maintain the definition of an AVL tree.
This page has more information: Weight-balanced tree - wikipedia
From Wikipedia:
A Binary Tree is called μ-balanced, with , if for every node N, the inequality:
holds and μ is minimal with this property. |N| is the number of nodes under the tree with N as root (including the root) and Nl is the left sub-tree of N.
Essentially, this means that the children in an AVL tree are not necessarily evenly distributed across the lowest level of the tree. Taking N as indicating the root node of the tree, one could construct a valid AVL tree that has more children to the left of the root than to the right of it. With a very deep tree, there could be many nodes at this bottom level.
The definition of an AVL tree would require that they all be within one of the deepest point, but makes no guarantee as to what node they are a child of with respect to a node N.
sibling nodes can have hugely differing numbers of descendants.
I was just scratching my head about this and the fact that my AVL implementation produced trees that were not ultimately lopsided, but which had smaller and larger "distant cousin" subtrees inside.
I sketched this out to reassure myself:
The red nodes have a balance of 1, the green ones -1, and the black ones 0. This is a valid AVL tree in that the height difference between two sibling subtrees is never more than one, but there are (almost) twice as many nodes in the right subtree as the left one.