Let's assume we create a Ternary tree using an array implementation. The root is stored in the index 1, the left child is stored in index = 3(index)-1, middle child is stored in 3(index), and right child is stored in 3(index)+1. So for example. Assume the following Ternary Tree.
A
B C D
E F G H I J K L M
The array implementation would be [None, A, B, C, D, E, F, G, H, I, J, K, L, M]
If we take F for random, F is the middle child go B, and B is the left child of A. A has an index of 1, so B has an index of 2, so F has an index of 6.
My question is, how can I get the depth from the indexes. F has an index of 6 and a depth of 2. If this was a binary tree, the depth would simply be equal to int(math.log(index, 2))
. What is the equation for the depth for a ternary tree, I can't think of any.
The formula is
int(math.log(2*index - 1, 3))
You can derive it as follows:
Each level has a number of nodes that is a power of 3. So the position of the last node in a level is a sum of such powers, which forms a geometric series. This means the index of the last node on level (zero based) is (3─1)/2. Solving this to , and taking into account the dummy entry in the array, this gives the final solution at the top.