If you have an index, you cannot find the depth.
Suppose you have a tree:
1 / \ 2 5 / \ 3 4
node with index 3 has a depth of 2.
Suppose you have a tree:
1 / \ 2 3 / \ 4 5
node with index 3 has a depth of 1.
You cannot distinguish between these two trees, knowing their indices. There is no way to find the distance from the root simply by knowing the index.
Edit: if you mean a perfect binary tree, as in, all the leaves are at the same depth, and each parent has two children, then you still cannot find the depth.
Compare these two trees:
1 / \ 2 3 1 / \ 2 5 / \ / \ 3 4 6 7
The depth of node 3 varies depending on the height of the tree.
Edit 2: if you know the height of the whole tree, you can use this recursive algorithm:
def distanceFromRoot(index, rootIndex, treeHeight): if index == rootIndex: return 0 leftIndex = rootIndex+1 rightIndex = rootIndex + 2**treeHeight if index >= rightIndex: return 1 + distanceFromRoot(index, rightIndex, treeHeight-1) else: return 1 + distanceFromRoot(index, leftIndex, treeHeight-1)
Kevin source share