最开始使用BFS代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(root == nullptr) return res;
        queue<TreeNode*> q;
        q.push(root);

        int round = 0;
        while(!q.empty())
        {
            int n = q.size();
            vector<int> num;
            
            for(int i = 0;i < n;i++)
            {
                TreeNode* curr = q.front();
                q.pop();
                
                if(round % 2 == 0)
                    num.push_back(curr->val);
                else
                    num.insert(num.begin(),curr->val);
                
                if(curr->left) q.push(curr->left);
                if(curr->right) q.push(curr->right);
            }
            round++;
            res.push_back(num);
        }
        return res;
    }
};

执行效率:

Runtime: 8 ms, faster than 18.57% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.
Memory Usage: 12.1 MB, less than 67.93% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.

上面的代码执行效率较差,因为调用了insert函数,参考BFS优化方法,优化后的代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(root == nullptr) return res;
        queue<TreeNode*> q;
        q.push(root);
        
        int round = 0;
        while(!q.empty())
        {
            int n = q.size();
            vector<int> num(n,0);
            
            for(int i = 0;i < n;i++)
            {
                TreeNode* curr = q.front();
                q.pop();
                
                if(round & 1)
                    num[n-1-i] = curr->val;
                else
                    num[i] = curr->val;
                
                if(curr->left) q.push(curr->left);
                if(curr->right) q.push(curr->right);
            }
            round++;
            res.push_back(num);
        }
        return res;
    }
};

运行效率:

Runtime: 4 ms, faster than 69.40% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.
Memory Usage: 12 MB, less than 84.57% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.