题目描述
- 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。如下图所示二叉树:
- 打印上图中二叉树的结果为:
8
6 10
5 7 9 11
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
解题思路
- 针对于此题,题目要求按行打印,即我们需要层次遍历这棵树
- 层次遍历树,使用队列数据结构,以层为单位进行入队,出队并打印
- 这里,我们可以考虑使用vector数据结构,将当前层的遍历结果存入到vector数组中,然后将每一层的结果存入一个vector中,这样我们利用一个嵌套for循环即可实现题目要求:将二叉树打印成多行
- 思路清晰后,我们就可以开始动手写代码了
代码实现
vector<vector<int> > Print(TreeNode* pRoot)
{
vector<vector<int>> res;
if(pRoot == NULL)
return res;
queue<TreeNode*> q;
q.push(pRoot);
while(!q.empty())
{
vector<int> level;
int sz = q.size();
while(sz--)
{
TreeNode* tmp = q.front();
q.pop();
level.push_back(tmp->val);
if(tmp->left != NULL)
q.push(tmp->left);
if(tmp->right != NULL)
q.push(tmp->right);
}
res.push_back(level);
}
}
void Print(vector<vector<int>> res)
{
if (res.empty())
return;
vector<vector<int>>::iterator it1;
vector<int>::iterator it2;
vector<int> it_tmp;
for (it1 = res.begin(); it1 != res.end(); it1++)
{
it_tmp = *it1;
for (it2 = it_tmp.begin(); it2 != it_tmp.end(); it2++)
cout << *it2 << " ";
cout << endl;
}
cout << endl;
}