剑指 Offer 32 - III. 从上到下打印二叉树 III
我的思路:由剑指 Offer 32 - II. 从上到下打印二叉树 II可以容易想到每次遍历一层后存下的tmp数组,用一个bool变量来判断从左到右还是从右到左,进行翻转
/**
* 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>> ans;
if (!root) return ans;
queue<TreeNode*> q;
q.push(root);
bool left = true;
while (!q.empty()) {
vector<int> tmp;
int num = q.size();
while (num--) {
TreeNode* top = q.front();
q.pop();
if (top->left) q.push(top->left);
if (top->right) q.push(top->right);
tmp.push_back(top->val);
}
if (!left){
reverse(tmp.begin(), tmp.end());
}
left = (left == true ? false: true);
ans.push_back(tmp);
}
return ans;
}
};

对官方解的思考: