您的位置:首页 > 职场人生

面试题60:把二叉树打印成多行

2017-04-28 22:51 369 查看
题目描述

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

解:

队列实现

/*
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)
return result;
int toBePrinted = 1;
int nextLevel = 0;
queue<TreeNode*> q;
q.push(pRoot);
vector<int> v;
while(!q.empty()){
TreeNode* pCur = q.front();
q.pop();
v.push_back(pCur->val);
--toBePrinted;
if(pCur->left){
q.push(pCur->left);
++nextLevel;
}

if(pCur->right){
q.push(pCur->right);
++nextLevel;

}
if(!toBePrinted){
result.push_back(v);
v.clear();
toBePrinted = nextLevel;
nextLevel = 0;
}
}
return result;
}

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