题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路:
1.把二叉树的根结点存入队列
2.如果存在子结点,子结点插入到队尾
3.从队首取出元素存入容器中
4.用两个变量记录当前层的结点数和下一层的结点数
5.当前层遍历结束时,当前层结点数为0,把该层结点存入vector中,继续进行下一层的遍历
6.循环上述过程直到队列为空
代码实现:
/*
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) {
/*
解题思路:
1.把二叉树的根结点存入队列
2.如果存在子结点,子结点插入到队尾
3.从队首取出元素存入容器中
4.用两个变量记录当前层的结点数和下一层的结点数
5.当前层遍历结束时,当前层结点数为0,把该层结点存入vector中,继续进行下一层的遍历
6.循环上述过程直到队列为空
*/
vector<int> result;
vector<vector<int> > ans;
int currentCount = 0,nextCount = 0;
if(pRoot == NULL){
return ans;
}
queue<TreeNode*> q;
TreeNode* currentNode;
q.push(pRoot);
currentCount++;
while(!q.empty()){
currentNode = q.front();
result.push_back(currentNode->val);
q.pop();
currentCount--;
if(currentNode->left != NULL){
q.push(currentNode->left);
nextCount++;
}
if(currentNode->right != NULL){
q.push(currentNode->right);
nextCount++;
}
if(currentCount == 0){
ans.push_back(result);
result.clear();
currentCount = nextCount;
nextCount = 0;
}
}
return ans;
}
};