I am the one who wrote OP. Finally, people understood my question. It's
always easy to assume the tree is "binary" whenever we talk about tree.
The nodes of list in problem look like this:
struct Object {
// THESE FIELDS ARE ALREADY DEFINED; YOU MAY NOT MODIFY THEM
Object* next_ptr; // Next object in list; NULL if end of
list.
unsigned int ID; // unique identifier for this object.
unsigned int parent_ID; // 0, if object is root of tree.
// THESE FIELDS REPRESENT THE TREE WHICH NEED TO BE FILLED
Object* parent_ptr; // Initialized as NULL.
unsigned int child_count; // Initialized as 0.
Object** child_ptr_array; // Initialized as NULL.
} ;
Need to implement the method:
Object* convert_List_To_Tree (Object* list_head);
By optimal I meant the solution that requires the least number of
scanning of list nodes with least extra space. My solution had one
scanning to find root which is O(n) in the worst case, another to count
number of children for a particulr node so that you know the value for
child_count and can initialize child_ptr_arry accordingly and then you
fill child_ptr_array. To fill child_ptry_array, I had two choices: one
to maintain a seperate list of children as I find child_count for a
particular node and put these nodes in child_ptr_array OR rescan the
list with num_children as counter. In rescanning of the list, I dint
start from the head but from the last node that I visited.
I wanted to see a better solution if it exists and of course some
analysis from you smart people. Thanks to you all with a special thanks
to Mr. Crueger and Mr.Harter.
By the way, I ran into this problem during one job interview. If it
makes you feel better, pls free to "brand" it as a homework problem.
cheers,
prabhat