您的位置:首页 > Web前端

剑指offer—把二叉树打印成多行

2015-10-08 21:39 429 查看
华电北风吹

天津大学认知计算与应用重点实验室

日期:2015/10/8

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

解析:这个跟按行打印一样的思路即可。

/*
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;
vector<int> temp;
TreeNode * flag = new TreeNode(NULL);
queue<TreeNode *> q;
q.push(pRoot);
q.push(flag);
while (true)
{
TreeNode * top = q.front();
q.pop();
if (top == flag)
{
result.push_back(temp);
temp.clear();
q.push(top);
top = q.front();
q.pop();
if (top == flag)
break;
}
temp.push_back(top->val);
if (top->left != NULL)
q.push(top->left);
if (top->right != NULL)
q.push(top->right);
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: