二叉树分层遍历(含之字形打印)
来源:互联网 发布:棺材 知乎 编辑:程序博客网 时间:2024/05/09 11:40
//二叉树结点定义
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;
}
}
}
- 二叉树分层遍历(含之字形打印)
- 之字形打印二叉树
- 之字形打印二叉树
- 之字形打印二叉树
- 之字形打印二叉树
- 按之字形打印二叉树
- 按照之字形打印二叉树
- 按之字形打印二叉树
- 按之字形打印二叉树
- 二叉树------之字形打印二叉树
- 按之字形顺序打印二叉树(二叉树的层次遍历)
- 分层打印二叉树
- 分层打印二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 寻找和为定值的多个数 【微软面试100题 第二十一题】
- 乐村淘电商平台 农村电商新模式 全国第一家村镇O2O服务平台
- thread join demo
- MySQL:日期函数、时间函数总结
- jsp标签库学习(二)tag标签
- 二叉树分层遍历(含之字形打印)
- Android进程的内存管理分析
- 如何从项目中移除storyboards
- App被拒的一些非常规问题总结
- Android 连接Wifi和创建Wifi热点 demo
- Oracle 11g 递归+ exists执行计划的改变
- regmap使用介绍
- Leetcode: Gas Station
- HDFS体系结构简介及优缺点