原题链接:剑指 Offer 32 - III. 从上到下打印二叉树 III
solution:
层序遍历,利用一个栈和flag标志实现顺序的转换
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root == NULL) return res;
queue<TreeNode *> que;
que.push(root);
int i = 1;
while(!que.empty()) {
int size = que.size();
vector<int> path;
stack<TreeNode *> stk;
while(size--) {
auto t = que.front();
que.pop();
path.push_back(t->val);
if(i % 2 == 0) {
if(t->right) stk.push(t->right);
if(t->left) stk.push(t->left);
} else {
if(t->left) stk.push(t->left);
if(t->right) stk.push(t->right);
}
}
while(!stk.empty()) {
que.push(stk.top());
stk.pop();
}
i++;
res.push_back(path);
}
return res;
}
};