Is there a way to store a complete binary tree in a table and browse this table with a formula without creating a tree?


For example, one way to do it is you could transform the tree into a complete binary tree, with null elements in place of previously non-existing elements (to fill out the tree), and starting at the root (1st array element) traverse it by going to the 2*ith + 1 element for left child and 2*ith + 2 element for right child. However, the array would be huge for a one-sided tree. Is there a more efficient way to do this?

I wrote my program to just traverse an array with the formula used above, 2N for left child, 2N+1 for right child. It is a guessing game that uses a “decision tree” to correctly guess an animal you think of. It asks yes or no questions to traverse a tree and eventually narrows down to one animal. If the animal isn’t the one you were thinking of, it asks for a question to differentiate between the new animal and the old one, and stores this new info in the tree.

In my implementation I didn’t use a tree, and to add new elements into the array I replaced the old answer with the question and added two spaces into the array for the two answers (children). I know it is inefficient to move the rest of the array forward to make a space for the new elements but I did that anyway. Then I realized that using the 2N+1 formula would be very inefficient for one-sided trees. So I am wondering if there is a way to structure the array or implement it so I can use some kind of formula for traversing it, and have it take up less space.

Normally the array variant is favourable and often used together with AVL-trees. These are binary search trees with a balancing method that guarantee that the tree stays balanced.

Clearly one could actually implement the tree like a list structure with separate objects that one links to.