Microsoft Interview Question
1,272 Interview Reviews |
Back to all Microsoft Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Development Engineer at Microsoft:
given binary tree inorder & preorder traversal, return postorder traversal
See more for this Microsoft Software Development Engineer Interview
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (2)
Here's some explanation: The first element on the "preorder" list will always be the root.
1. Find that element in the inorder list and split it.
2. Pop the element from the pre-order list. There you go, just apply recursion now. The following element on the pre-order list will be the new root of either "leftList" or "rightList" (if leftList is empty). Just recursively apply this algorithm on the new lists.
function postOrder(preOrder, inOrder, result) {
var root = preOrder[0];
var splitArray;
var rootIndexInOrder;
var leftElements;
var rightElements;
preOrder.splice(0,1);
for(var i = 0; i < inOrder.length; ++i) {
if(inOrder[i] === root) {
rootIndexInOrder = i;
break;
}
}
leftElements = inOrder.slice(0, rootIndexInOrder);
rightElements = inOrder.slice(rootIndexInOrder+1);
if(leftElements.length !== 0) {
postOrder(preOrder, leftElements, result);
}
if(rightElements.length !== 0) {
postOrder(preOrder, rightElements, result);
}
result.push(root);
}
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up



0 of 1 people found this helpful
by Interview Candidate: