Microsoft Interview Question
Software Engineer in TestsI agree with Musheka. Because it's a binary tree, the solution is sketched out like this:
void traverse(node* &pnode){
if (pnode == NULL) return;
//get the left child
node *left = pnode->leftChild;
//get the right child
node *right = pnode->rightChild;
//populate the nextRight
left->nextRight = right;
right->nextRight = null;
traverse(left);
traverse(right);
}
call traverse(root);
@Silence: But what happens if the parent of a node doesn't have a right child ? left->nextRight will be null. But there may be a nextRight node on the same level with a different parent.
I think doing a BFS and then linking the nodes at each level as we encounter them is the way to do it.
Another interpretation is, nextRight means the next sibling node to the right.
In this case, do a BFS and chain together nodes of the same level.
If nextRight points to the next node to the current node in the same level:
1 void populate(Node * root)
2 {
3 if(!root)
4 return;
5 Node * left = root->left;
6 Node * right = root->right;
7 if(left)
8 left->nextRight = right;
9 if(right)
10 right->nextRight = (root->nextRight) ? NULL : root->nextRight->left;
11 populate(left);
12 populate(right);
13 }
Basic idea:
In order to link all nodes in the same level, we have to traversal nodes by level. For each level, we traverse from the most right node to the most left node using a queue and build a list for each level.
37 void connect_nodes_by_level(Node * root)
38 {
39 if(!root)
40 return;
41 queue<Node*> q;
42 q.push(root);
43 int nump = 1;
44 int numc = 0;
45 Node * p = NULL;
46 while(nump)
47 {
48 Node * n = q.front();
49 q.pop();
50 n->nextRight = p;
51 p = n;
52 nump--;
53 if(n->right)
54 {
55 q.push(n->right);
56 numc++;
57 }
58 if(n->left)
59 {
60 q.push(n->left);
61 numc++;
62 }
63 if(!nump)
64 {
65 nump = numc;
66 numc = 0;
67 p = NULL;
68 }
69 }
Keep a static pointer tmp in breadth first traversal and set tmp to root at starting. than set temp->nextright to node popped from queue. and set tmp to newly popped node. At the end you will get a tree with all levels connected left to right and right most node connected to left node of next level. so now set null in all right most nodes.
I agree with Musheka. Because it's a binary tree, the solution is sketched out like this:
- Anonymous January 12, 2010