题目描述:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
题目解析:
采用层序遍历的思想。将节点push进队列中,当队列不为空时,增加两个变量,一个用来计数,一个用来获取当前队列中的节点个数。当计数小于总数时,说明这些节点在一层中,将这些节点push_back进vector1中。再遍历当前结点的左子树和右子树,将vector1 push_back 进vector2中。队列不为空,再进行循环。
/*
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 > > v;
if(pRoot == NULL)
return v;
queue<TreeNode*> q;
int index,size;
q.push(pRoot);
while(!q.empty())
{
index = 0;
size = q.size();
vector<int> tmp;
while(index < size)
{
index++;
TreeNode* front = q.front();
q.pop();
tmp.push_back(front->val);
if(front->left)
q.push(front->left);
if(front->right)
q.push(front->right);
}
v.push_back(tmp);
}
return v;
}
};
(*^▽^*)