Binary trees: Getting the path of an element from its signature

半腔热情 提交于 2019-12-11 14:19:39

问题


Assume you have a binary tree which classifies images. Each node is a different binary test. When an image is fed to the tree, a unique path through the tree is generated.

A path is described as a binary word which is as long as the depth of the tree.

For instance, for a 2-stage binary tree, an example of path would be (0,1) ((left,right) thus ending in the second leaf of the tree from the left).

We also assume that for any image being fed to the tree, all node tests are executable. Thus, we can define a signature for any image: this signature is a binary word which length is the number of nodes.

For instance, for a 2-stage binary tree, an example of signature would be s = {0,1,1}

s[i] is the binary result from the test of the ith node.

I am looking for a way to get the path of an image from its signature.

A naive way of doing it would be to jump from index to index of the signature with appropriate decreasing leap length.

However, I wonder if there could be a bitwise calculation which could yield the result (The indexes in the signature can be reorganized if necessary).

Is this possible? If yes, how?


回答1:


With 1 stage there is 1 test.

With 2 stages there are 1+2 tests.

With 3 stages there are 1+2+4 tests.

With 4 stages there are 1+2+4+8 tests.

With 5 stages there are 1+2+4+8+16=31 tests.

One approach to computing the path faster is to test the first bit, and then extract the corresponding set of 15bits that map to the next 4 stages. There are only 2**15=32768 different choices so the path can be looked up in a table.

Pseudocode:

 if (x&(1<<30))
    x >>= 15;
 path = lookup[x & 0x7fff];

lookup is a 2**15 length array that you can precalculate.



来源:https://stackoverflow.com/questions/37852911/binary-trees-getting-the-path-of-an-element-from-its-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!