Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a Logarithm to Navigate a Tree

I had once known of a way to use logarithms to move from one leaf of a tree to the next "in-order" leaf of a tree. I think it involved taking a position value (rank?) of the "current" leaf and using it as a seed for a fresh traversal from the root down to the new target leaf - all the way using a log function test to determine whether to follow the right or left node down to the leaf.

I no longer recall how to exercise that technique. Can anyone re-introduce me?

I also don't recall if the technique required the tree to be balanced, or if it worked on n-trees or only binary trees. Any info would be appreciated.

like image 376
Brent Arias Avatar asked Sep 21 '10 21:09

Brent Arias


1 Answers

Since you mentioned whether to go left or right, I'm going to assume you're talking about a binary tree specifically. In that case, I think you're right that there is a way. If your nodes are numbered left-to-right, top-to-bottom, starting with 1, then you can find the rank (depth in the tree) by taking the log2 of the node's number. To find that node again from the root, you can use the binary representation of the number, where 0 = left and 1 = right.

For example:

  • n = 11

  • 11 in binary is 1011

  • We always ignore the first 1 since it's going to be there for every number (all nodes of rank n will be binary numbers with n+1 digits, with the first digit being 1). We're left with 011, which is saying from the root go left, then right, then right.

If you want to find the next in-order leaf, take the current leaf's number and add one, then traverse from the root using this method.

I believe this only works with balanced binary trees.

like image 79
Colin Avatar answered Sep 28 '22 01:09

Colin