您的位置:首页 > Web前端

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

2016-05-23 10:30 344 查看


题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
分析:层序遍历用队列,这道题比较讨厌的是要把每层分开,如果只是单纯把值全部打印出来,只要判断队列是否为空就可以了,这里需要判断已经打印的个数是不是这一层的总个数。

代码:

/*
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) {
queue<TreeNode*> q;
vector<vector<int> > ret;
if(pRoot==NULL) return ret;
q.push(pRoot);
helper(ret,q);
return ret;
}
void helper(vector<vector<int> > &ret,queue<TreeNode*> &q){
while(!q.empty()){
vector<int> path;
int n=q.size();
int i=0;
while(i<n){
TreeNode* temp=q.front();
path.push_back(temp->val);
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
q.pop();
i++;
}
ret.push_back(path);
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: