整理自剑指Offer
一:题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行
二:解题思路
层次遍历二叉树,用队列保存将要打印的结点
需要用到两个变量:
1.表示当前层中还没有打印的结点的数
2.表示下一层节点的数目
三:代码实现
非递归实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > result;
if(pRoot==NULL)
return result;
queue<TreeNode*> q;
q.push(pRoot);
int printNodeSum=1;
int nextNodeSum=0;
vector<int> rowNode;
while(!q.empty()){
//获取队首元素
TreeNode* pCurrentNode=q.front();
//保存当前节点
rowNode.push_back(pCurrentNode->val);
if(pCurrentNode->left){
q.push(pCurrentNode->left);
nextNodeSum++;
}
if(pCurrentNode->right){
q.push(pCurrentNode->right);
nextNodeSum++;
}
//出队
q.pop();
printNodeSum--;
//如果当前行打印结束
if(printNodeSum==0){
result.push_back(rowNode);
rowNode.clear();
printNodeSum=nextNodeSum;
nextNodeSum=0;
}//if
}//while
return result;
}
};