Use two counters to differ continues levels, put NULL in the stack to differ two continues levels
bool foo(tree* root)
{
if(!root) return false;
queue
stack
q.push(root);
int c1=1;
int c2=0;
while(!q.empty())
{
tree* node=q.front();
q.pop();
s.push(node);
c1--;
if(c1==0) {node=NULL;s.push(node);}
if(node->right)
{
q.push(node->right);
c2++;
}
if(node->left)
{
q.push(node->left);
c2++;
}
if(c1==0) {c1=c2;c2=0;}
}
while(!s.empty())
{
tree* node=s.top();
s.pop();
if(node) cout< < node->val;
else cout< < endl;
}
return true;
}
No comments:
Post a Comment