题目:从上到下打印出二叉树的每个结点,同一层结点按照从左到右的顺序打印。
这道题的实质是二叉树的层序遍历,借助队列来实现。
#include <queue>
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > v;
if (pRoot == NULL)
return v;
queue<TreeNode*> q;
q.push(pRoot);
while (!q.empty())
{
int size = q.size();
vector<int> tmp;
for (int i = 0; i < size; ++i)
{
TreeNode* pCur = q.front();
tmp.push_back(pCur->val);
if (pCur->left)
q.push(pCur->left);
if (pCur->right)
q.push(pCur->right);
q.pop();
}
v.push_back(tmp);
}
return v;
}
};