Each node of the tree might have an arbitrary number of children. I need a way to construct and traverse such trees, but to implement them using one dimensional vector or a list.
In array representation of a binary tree, we use one-dimensional array (1-D Array) to represent a binary tree. Consider the above example of a binary tree and it is represented as follows... To represent a binary tree of depth 'n' using array representation, we need one dimensional array with a maximum size of 2n + 1.
A binary tree has a special condition that each node can have a maximum of two children. A binary tree has the benefits of both an ordered array and a linked list as search is as quick as in a sorted array and insertion or deletion operation are as fast as in linked list.
Trees can be represented in two ways as listed below: Dynamic Node Representation (Linked Representation). Array Representation (Sequential Representation).
If you only can use one vector (not specified in question), and Nodes should not contain it's own list, only some pointers (addresses in vector), then you can try this:
So for tree like this:
A
| \
B E ___
|\ \ \ \
C D F G H
Your vector would look like:
idx: 0 1 2 3 4 5 6 7
nodes: A B C D E F G H
next: _ 4 3 _ _ 6 7 _
where _
is null pointer
Edit:
Another approach:
For that approach given tree would look like:
idx: 0 1 2 3 4 5 6 7 8 9 A B
nodex: A _ B E _ C D _ F G H _
child: 2 5 8 _ _ _ _ _
That way you can easily find children of any randomly given node and reorganize array without moving all elements (just copy children to end of table, update pointer and add next child to end of table)
The standard way of storing a full binary tree in an array (as is used for binary heap implementations) is nice because you can represent the tree with an array of elements in the order of a level-order tree traversal. Using that scheme, there are quick tricks for computing the parent and child node positions. Moving to a tree in which each node can have an arbitrary number of elements throws a wrench into that kind of scheme.
There are, however, several schemes for representing arbitrary trees as binary trees. They are discussed in great detail in Donald Knuth's Art of Computer Programming, Volume I, Section 2.3.
If the nodes themselves are permitted to contain a pointer, you could store a list of child indicies for each node. Is that possible in your case?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With