跳转至

103.Binary Tree Zigzag Level Order Traversal

Tags: Tree Medium

Link: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/


Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example: Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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

Answer:

/**
 * 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:
    //相比于102,可以认为是奇数层反转,所以增加一个times来记录层数(root是第0层)
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> result;
        if(root == nullptr) return result;

        queue<TreeNode *> cur;
        cur.push(root);
        int times = 0;

        while(!cur.empty()){
            vector<int> tmp;

            for(int i = cur.size(); i > 0; --i){
                TreeNode *p = cur.front();
                cur.pop();
                tmp.push_back(p -> val);

                if(p ->left != nullptr) cur.push(p -> left);
                if(p -> right != nullptr) cur.push(p -> right);
            }
            if(times & 1) reverse(tmp.begin(), tmp.end());
            result.push_back(tmp);
            ++times;
        }

        return result;
    }
};

这种思路比较简单,注意32行判断是否是偶数的时候采取位运算,速度可以提高4ms左右。但是仍然存在优化的空间,因为每次遍历每一层时,存储每层元素的数组的大小是确定的,就是q.size(),所以可以直接确定每层元素在对应数组的位置,这样就免于翻转数组。

/**
 * 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>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if (!root) return res;

        queue<TreeNode *> q;
        q.push(root);
        int floor = 0;
        while (!q.empty()) {
            int len = q.size();
            vector<int> level(len);
            for (int i = q.size(); i > 0; --i) {
                TreeNode * p = q.front();
                q.pop();
                if (floor & 1) level[i - 1] = p -> val;
                else level[len - i] = p -> val;
                if (p -> left) q.push(p -> left);
                if (p -> right) q.push(p -> right);
            }
            res.push_back(level);
            ++floor;
        }

        return res;
    }
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.
Memory Usage: 13.5 MB, less than 90.70% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.