//二叉树结点定义
struct TreeNode
{int data;
TreeNode *left;
TreeNode *right;
};
(一)分层打印:从左到右
方法一:利用vector代替数组,可利用到其动态扩展的特性
void PrintNodeByLevel(TreeNode *root){
if(root==NULL)
return;
vector<TreeNode *>vec;
vec.push_back(root);
int cur=0,last=1;
while(cur < vec.size())
{
last=vec.size();
while(cur<last)
{
cout<<vec[cur]->data<<" ";
if(vec[cur]->left)
vec.push_back(vec[cur]->left);
if(vec[cur]->right)
vec.push_back(vec[cur]->right);
cur++;
}
cout<<endl;
}
}
方法二:利用队列保存要打印的结点
void PrintNodeByLevel2(TreeNode *root)
{
if(root==NULL)
return;
queue<TreeNode *>que;
que.push(root);
int nextLevel=0; //下一层的结点数
int toBePrinted=1; //当前层还没打印的节点数
while(!que.empty())
{
TreeNode *node=que.front();
cout<<node->data<<" ";
//如果一个结点有子结点,我们把每个子结点加到队列中,同时将nextLevel加1
if(node->left!=NULL)
{
que.push(node->left);
++nextLevel;
}
if(node->right!=NULL)
{
que.push(node->right);
++nextLevel;
}
que.pop();
--toBePrinted;
if(toBePrinted==0) //toBePrinted变为0时,当前层打印完毕
{
cout<<endl;
toBePrinted=nextLevel;
nextLevel=0;
}
}
}
(二)分层遍历:之字形打印
void PrintfNodeByLevel(TreeNode *root)
{
if(root==NULL)
return;
stack<TreeNode *> lev[2];
int cur=0;
int next=1;
lev[cur].push(root);
while(!lev[0].empty() || !lev[1].empty())
{
TreeNode *node=lev[cur].top();
lev[cur].pop();
cout<<node->data;
if(cur==0)
{
if(node->left!=NULL)
lev[next].push(node->left);
if(node->right!=NULL)
lev[next].push(node->right);
}
else
{
if(node->right!=NULL)
lev[next].push(node->right);
if(node->left!=NULL)
lev[next].push(node->left);
}
if(lev[cur].empty())
{
cout<<endl;
cur=1-cur;
next=1-next;
}
}
}