问题
I have a balanced binary tree structure:
Node 0
at depth 0
is the root.
The root's left child is 1
and right child is 2
, and so on.
Please see image:
The total depth of the tree is given as N
. This N
is the only parameter of the problem. Nodes at level N
are designated as leaf nodes.
I am storing this tree using the following node structure.
struct node_s{
int n, depth, parent;//n is node number
int nodescendents;//number of descendents of the current node
std::vector<int> descendents;//Descendents in ascending order
int lchild, rchild;//Immediate left child and right child
std::vector<int> lchildleaves;//leaf nodes that descend from the immediate
//left child
std::vector<int> rchildleaves;//leaf nodes that descend from the immediate
//right child
};
I intend to store the tree itself as:
std::vector<node_s> tree;
Is there a way to numerically efficiently populate the tree
vector using simple algebra roughly as:
//Creating the nth node, beginning from 0th node, then 1st node and so on
nodes_s node;
//populate all data structures of the nth node
//precisely, here, there are loops, algebraic calculations, etc., that can help
//populate all of the node_s data members.
tree.push_back(node);
The only way I can think of as of now is to construct a graph explicitly and run some sort of Dijkstra algorithm to figure out these data structure values for each node.
回答1:
For a node k
, the key point is to identify its position in the graph, in order to identify its parent, if it is a left or right child.
For node k, its rank r[k] is equal to floor(log2(k+1)) and its position in the rank is equal to p[k] = k - 2^r[k] + 1
Then k is located by the pair (r[k], p[k])
Conversely, k = 2^r[k] + p[k] - 1
Its parent is then located by (r[k]-1, floor(p[k]/2)) -> node index = 2^r + p - 1
k is a left child if k%2 == 1
I guess the rest is rather easy
来源:https://stackoverflow.com/questions/53349791/are-there-any-efficient-ways-to-populate-a-balanced-tree-structure