10
/ \
5 20
/ \ /
3 6 15
~~~~ TO ~~~~
10
/ \
5 ----> 20
/ \ /
3---> 6-->15
Answer:
Here is a solution of time and spacecomplexity O(n)
Here we do a breadth first search using a queue, and maintain the previous
node and its depth to create the linked list.
struct Node
{
int val;
Node *next;
Node *left;
Node *right;
};
void LinkifyTree(Node* root)
{
Queue q;
// contains the node and the depth at which the node occurs.
typedef pairNodeInfo;
// the previous node and its depth.
Node *prev_node = NULL;
int prev_depth = -1;
q.enqueue(make_pair(root,0));
while( !q.isempty())
{
NodeInfo ni = q.dequeue();
if (prev_node && (prev_depth == ni.second) )
{
/* previous node exists and the depth of the previous
* node is equal to the current node
* */
prev_node->next = ni.first;
}
else
{
ni.first->next = NULL;
}
prev_node = ni.first;
prev_depth = ni.second;
/* add the child nodes along with the depth */
q.enqueue( make_pair(ni.first->left, ni.second+1) );
q.enqueue( make_pair(ni.first->right, ni.second+1) );
}
}
No comments:
Post a Comment