Compute the average distance from a node to the root in a worst-case tree of
2^n nodes built by the weighted quick union algorithm?
This is an exercise in Algorithm in C++(Robert Sedgewick).
I know the worst case distance but can someone suggest me correct way to compute average distance?
Worst case scenario is the merging of 2 tree with same number of nodes. lets say merge 2 tree each having 2^n nodes, resulting tree [=size 2^(n+1) nodes] will have n+1 max distance of any node from the root ( more than 1 after merge).
In worst case- if tree size is 2^n, distance from root to any of the node is always less than n.
How can we calculate the average distance if the max distance is n for 2^n node tree?
The worst case is as you said, you always add two trees of the same height. In order to achieve it, you need: 2 trees of height n-1, and to achieve it you need 4 trees of height n-2, ….
At the end, you need n trees of height 1, n/2 trees of height 2, …, 1 tree of height n.
Since this is your homework, I will be done by hinting you how to continue:
Use the prvious observation, and follow the algorithm to build the trees and “achieve” worst case. Note how many leaves there are in each depth – if you build a tree this way [start with examples of private cases, n=1,2,3 and see how it “behaves”]
If you need to formally prove it – it should be probably done by induction on the height [n].