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 number of nodes in level
kis3**k, for level 0 it's 1, for level 1 it's 3, for level 2 it's 9, and so on. The total number of nodes inklevels is the sum of arithmetic progression:For a node index
Nyou need to find suchkthat:I would suggest binary search to find
kgivenN, as it's a programming problem, not mathematical.But you can also try to solve the equation by taking the natural logarithm of its parts, for
N>1it should keep the inequality sign. I'll leave this to you as an excersize, otherwise you can ask in the Mathematics stack exchange.