利用两个队列,还有一道题是之字形输出二叉树,是用两个栈,步骤基本相同。
/*
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> > res;
if(pRoot == NULL)
return res;
vector<int > v;
queue<TreeNode *> q1;
queue<TreeNode *> q2;
q1.push(pRoot);
while(!q1.empty() || !q2.empty())
{
v.clear();
if(q2.empty())
{
while(!q1.empty())
{
TreeNode * temp;
temp = q1.front();
q1.pop();
v.push_back(temp -> val);
if(temp -> left != NULL)
q2.push(temp -> left);
if(temp -> right != NULL)
q2.push(temp -> right);
}
res.push_back(v);
}
else
{
while(!q2.empty())
{
TreeNode * temp;
temp = q2.front();
q2.pop();
v.push_back(temp -> val);
if(temp -> left != NULL)
q1.push(temp -> left);
if(temp -> right != NULL)
q1.push(temp -> right);
}
res.push_back(v);
}
}
return res;
}
};