Microsoft Interview Question
Only one data structure <deque> is needed.
Test passed.
void print(Node* node){
deque<Node*> deq;
if (!node)
return;
deq.push_back(node);
for (deque<Node*>::const_iterator it=deq.begin();it!=deq.end();++it){
if ((*it)->left!=NULL)
deq.push_back((*it)->left);
if ((*it)->right!=NULL)
deq.push_back((*it)->right);
}
for (deque<Node*>::reverse_iterator it=deq.rbegin();it!=deq.rend();++it)
cout<<(*it)->value;
}
void Tree::PrintLevels(TNode* root)
{
if( root == NULL)
return;
queue<TNode*> q;
stack<int> st;
q.push(root);
while(!q.empty())
{
TNode* node = (TNode*)q.front();
q.pop();
st.push(node->data);
if(node->right)
q.push(node->right);
if(node->left)
q.push(node->left);
}
while(!st.empty())
{
printf("%d",st.top());
st.pop();
}
}
Absolutely..using a queue plus a stack is the way to do this.
- Anonymous August 29, 2008You can do it like this..
Read the root value. Add it to the queue. Then delete the element from the queue, add it to the STACk and add the Right child and Left child to the queue. Keep doing this until the queue is empty. POP the STACk and you have your answer.