题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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) {
vector<vector<int>> result{};
queue<TreeNode*> que{};
if(pRoot==nullptr) return result;
que.push(pRoot);
int level=0;
while(!que.empty()){
int n=que.size();
vector<int> temp{};
for(int i=0;i<n;i++){
auto node=que.front();
temp.push_back(node->val);
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
if(level%2==0) result.push_back(temp);
else{
reverse(temp.begin(),temp.end());
result.push_back(temp);
}
level++;
}
return result;
}
};