[recommend for beginners]clean C++ implementation with detailed explanation


  • 7
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> result;
            if(!root) return result;
            deque<TreeNode*> tree;
            tree.push_back(root);
            int flag=0;
            while(!tree.empty()){
                int count=tree.size();
                vector<int> level;
                while(count-- > 0){
                    TreeNode* cur=tree.front();
                    tree.pop_front();
                    level.push_back(cur->val);
                    if(cur->left) tree.push_back(cur->left);
                    if(cur->right) tree.push_back(cur->right);
                }
                if(flag & 1) reverse(level.begin(), level.end());
                result.push_back(level);
                flag++;
            }
            return result;
        }
    };

  • 9
    G

    I like the detailed explanation of this post ;-)


  • 0
    G

    damn detailed...


  • 0
    M

    @guyarad Lmao


Log in to reply
 

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