Microsoft Interview Question
1,268 Interview Reviews |
Back to all Microsoft Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Development Engineer In Test (SDET) at Microsoft:
Given the root of a binary search tree, link all the nodes at the same level, by using an additional Node* level.
| Tags: | c++ See more , See less 8 |
See more for this Microsoft Software Development Engineer In Test (SDET) Interview
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (2)
Queue<T> q = new Queue<T>();
q.Enqueue(root);
int count = 1;
int nextCount = 0;
T prev = null;
while (!q.Empty())
{
T cur = q.Dequeue();
if (prev != null)
{
// doubly-link level siblings
prev.rightSibling = cur;
cur.leftSibling = prev;
}
count--;
if (count == 0)
{
// next level
count = nextCount;
nextCount = 0;
prev = null;
}
else
{
// same level
prev = cur;
}
if (cur.Left != null)
{
nextCount++;
q.Enqueue(cur.Left);
}
if (cur.Right != null)
{
nextCount++;
q.Enqueue(cur.Right);
}
}
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up



1 of 1 people found this helpful
by Interview Candidate:
put all the nodes in a queue,
keep track of number of nodes at current level and at next level by counting,
dequeue a node from the queue,
put its left and right children in the queue by updating your counts,
using your counts, connect the nodes at the same level.
O(N) in both time and space.