Share my C++ solution,easy to understand


  • 0
    V
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> ret;
            if (root == NULL)
                return ret;
                
            queue<TreeNode *> q;
            int left_to_right = 1;
            int cnt = 0;
            
            q.push(root);
            while(!q.empty())
            {
                vector<int> vec;
                cnt = q.size();
                
                while(cnt--)
                {
                    TreeNode *temp = q.front();
                    q.pop();
                    vec.push_back(temp->val);
                        
                    if (temp->left != NULL)
                        q.push(temp->left);
                    if (temp->right != NULL)
                        q.push(temp->right);
                }
                
                if (left_to_right == 1)
                {
                    left_to_right = 0;
                    ret.push_back(vec);
                }
                else
                {
                    left_to_right = 1;
                    reverse(vec.begin(), vec.end());
                    ret.push_back(vec);
                }
            }
            
            return ret;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.