- 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
- 这不就层序遍历吗,So Easy !只不过要按每层来输出,普通层序遍历的话用队列即可实现,这道题要按行输出就得用两个队列。
- C++
/*
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;
queue<TreeNode*> queueA;
queue<TreeNode*> queueB;
TreeNode* nodeTemp;
vector<int> line;
queueA.push(pRoot);
while(!queueA.empty() || !queueB.empty()){
line.clear();
while(!queueA.empty()){
nodeTemp = queueA.front();
queueA.pop();
if(nodeTemp->left) queueB.push(nodeTemp->left);
if(nodeTemp->right) queueB.push(nodeTemp->right);
line.push_back(nodeTemp->val);
}
if(!line.empty()) result.push_back(line);
line.clear();
while(!queueB.empty()){
nodeTemp = queueB.front();
queueB.pop();
if(nodeTemp->left) queueA.push(nodeTemp->left);
if(nodeTemp->right) queueA.push(nodeTemp->right);
line.push_back(nodeTemp->val);
}
if(!line.empty()) result.push_back(line);
}
return result;
}
};