Adobe Interview Question
Software Engineer / Developersq.push_back(root)
while (q is not empty) {
node = q.pop_front();
s.push(node)'
if (node->left) {
q.push_back(node->left)
}
if (node->right) {
q.push_back(node->right)
}
}
while (S !empty) {
pop and print.
}
There is a little problem in there. The tree you print is from right to left, which is not very correct. Tiny change:
q.push_back(root)
while (q is not empty) {
node = q.pop_front();
s.push(node)'
if (node->right) {
q.push_back(node->right)
}
if (node->left) {
q.push_back(node->left)
}
}
while (S !empty) {
pop and print.
}
1. Start from root and enqueue to the queue.
2. Dequeue an element and push it to the stack.
3. Enqueue the children from the dequeued node(from step 2).
4. Repeat step 2 and 3 until you reach the leaves.
5. Now print the stack by popping elements until it gets empty.
Hope it's correct! :)
Use "reverse-dfs" to solve the problem.
@ Akash, where did you copy those code chunks from?seems to be from some data structure book. anyways that does the same thing as I mentioned above.
Look at below link for solution...
- Akash December 05, 2008http://tech-queries.blogspot.com/2008/12/level-order-tree-traversal-in-reverse.html