4 ms·
EDIT: Actually, in retrospect, this is not quite right. It maps every tree to a natural number, but not every natural number to a tree. Regardless, it can be ha
by lalaland1125 8y ago
EDIT: Actually, in retrospect, this is not quite right. It maps every tree to a natural number, but not every natural number to a tree. Regardless, it can be handy in certain circumstances.
Another simpler way of doing this is to encode a tree with n levels as 2^n - 1 bits. The first bit is 1 if and only if this tree has a root. The next 2^(n-1) - 1 bits represent the left tree. The following 2^(n-1) - 1 bits represent the right tree. Recurse as needed until you get to a tree with only one level (which is either a single node when the bit is 1, or is nothing when the bit is 0).
I'm fairly sure this is not optimal, but it is much simpler.
- User23 8y agoThis is quite like the trick for flattening binary trees into an array.
- deleted 8y ago[deleted]
- rexpan 8y ago> It maps every tree to a natural number, but not every natural number to a tree. This is a one-to-one mapping between binary trees and natural numbers. This encode an n level tree with O(n) bits