Clean 3ms C++ BFS


  • 0

    Idea is simple: BFS, only select the last node of current level.

        vector<int> rightSideView(TreeNode* root) {
            vector<int>res;
            if(!root) return res;
            deque<TreeNode*>cur_level;
            deque<TreeNode*>next_level;
            cur_level.push_back(root);
    
            while(!cur_level.empty()){
                TreeNode* node = cur_level.front();
                cur_level.pop_front();
                
                if(node->left) next_level.push_back(node->left);
                if(node->right) next_level.push_back(node->right);
                
                if(cur_level.empty()){
                    res.push_back(node->val);
                    swap(cur_level, next_level);
                }
            }
            return res;
        }
    

Log in to reply
 

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