题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/*
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*> que;
vector<vector<int>> res;
int flag=0;
if(pRoot==nullptr) return res;
que.push(pRoot);
while(!que.empty())
{
int s=que.size();
vector<int> path;
for(int i=0;i<s;i++)
{
auto tmp=que.front();
path.push_back(tmp->val);
que.pop();
if(tmp->left) que.push(tmp->left);
if(tmp->right) que.push(tmp->right);
}
if(flag==0)
{
res.push_back(path);
flag=1;
}
else
{
reverse(path.begin(),path.end());
res.push_back(path);
flag=0;
}
}
return res;
}
}; 
查看12道真题和解析