Simple C++ solution(6ms)


  • 0
    Y
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> res;
            if(!root) return res;
            vector<TreeNode*> nodes(1,root);
            helper(res,nodes,true,0);
            return res;
        }
    private:
        void helper(vector<vector<int>> & res,vector<TreeNode*> nodes,bool to_right,int level ){
            if(res.size()==level) res.push_back(vector<int>());
            vector<TreeNode*> new_nodes;
            for(int i=0;i<nodes.size();i++){
                int k = to_right? i:nodes.size()-1-i;
                res[level].push_back(nodes[k]->val);
                if(nodes[i]->left)new_nodes.push_back(nodes[i]->left);
                if(nodes[i]->right)new_nodes.push_back(nodes[i]->right);
            }
            if(new_nodes.empty()) return;
            helper(res,new_nodes,!to_right,level+1);
        }
    };
    

Log in to reply
 

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