【刷题之路】二叉树按层打印
2016-05-30 21:05
246 查看
按层打印,换层换行
class TreePrinter {
public:
vector<vector<int> > printTree(TreeNode* root) {
// write code here
TreeNode* last;
TreeNode* nlast;
vector<int> temp; //用于保存每一层的值
queue<TreeNode*> tmp; //用于保存遍历的树节点
vector<vector<int> > res;
last=root;
nlast=root;
tmp.push(root);
while(!tmp.empty()){
last=tmp.front(); //last为队列的头,即为遍历的节点
tmp.pop();
temp.push_back(last->val);
if(last->left) tmp.push(last->left); //将当前遍历的节点的左右子节点放入队列中
if(last->right) tmp.push(last->right);
if(last==nlast){
nlast=tmp.back(); //当last==nlast,下一层的所有节点必然已经全部放入队列中,于是让nlast=tmp的末尾,即为下一行的最后一个节点
res.push_back(temp);
temp.clear();
}
}
return res;
}
};
class TreePrinter {
public:
vector<vector<int> > printTree(TreeNode* root) {
// write code here
TreeNode* last;
TreeNode* nlast;
vector<int> temp; //用于保存每一层的值
queue<TreeNode*> tmp; //用于保存遍历的树节点
vector<vector<int> > res;
last=root;
nlast=root;
tmp.push(root);
while(!tmp.empty()){
last=tmp.front(); //last为队列的头,即为遍历的节点
tmp.pop();
temp.push_back(last->val);
if(last->left) tmp.push(last->left); //将当前遍历的节点的左右子节点放入队列中
if(last->right) tmp.push(last->right);
if(last==nlast){
nlast=tmp.back(); //当last==nlast,下一层的所有节点必然已经全部放入队列中,于是让nlast=tmp的末尾,即为下一行的最后一个节点
res.push_back(temp);
temp.clear();
}
}
return res;
}
};
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- C语言二叉树的非递归遍历实例分析
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析