4ms C++ Solution using BFS


  • 0
    E
    class Solution {
    public:
    
        void BFS(TreeNode* root,vector<vector<int>> & res, queue<TreeNode*> & q){
            int depth=0;
            while(!q.empty()){
                vector<int> tmp;
                int size=q.size();
                for(int i=0;i<size;i++){
                    TreeNode* cur=q.front();q.pop();
                    tmp.push_back(cur->val);
                    if(cur->right) {q.push(cur->right);}
                    if(cur->left) {q.push(cur->left);}
                }
                if(depth%2==0){
                    reverse(tmp.begin(),tmp.end());
                }
                depth++;
                res.push_back(tmp);
                tmp.clear();
            }
        }
        
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> res;
            if(root==NULL) return res;
            queue<TreeNode*> q;
            q.push(root);
            BFS(root,res,q);
            return res;
        }
    };
    

Log in to reply
 

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