思路:层次遍历,并且在层次遍历过程中添加一个标志,调整每一层元素的顺序。
/*
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;
}
};