【剑指Offer】面试题32 - III. 从上到下打印二叉树 III

题目

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [20,9],
  [15,7]
]
``` 

提示:
节点总数 <= 1000

## 思路
在[【面试题32 - II. 从上到下打印二叉树 II】](https://www.cnblogs.com/galaxy-hao/p/12369542.html)基础上偶数层逆序即可。

### 代码
时间复杂度:O(n)
空间复杂度:O(n)
```cpp
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if (root) {
            queue<TreeNode*> que;
            que.push(root);
            int line = 1;
            while (!que.empty()) {
                int size = que.size();
                vector<int> tmp;
                while (size--) {
                    TreeNode *node = que.front();
                    que.pop();
                    tmp.push_back(node->val);
                    if (node->left) que.push(node->left);
                    if (node->right) que.push(node->right);
                }
                if (line % 2 == 0) {
                    reverse(tmp.begin(), tmp.end()); //偶数层逆序
                }
                res.push_back(tmp);
                ++line;
            }
        }
        return res;
    }
};
posted @ 2020-02-26 22:30  Galaxy_hao  阅读(120)  评论(0编辑  收藏  举报