My BFS cpp code


  • 0
    C
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) 
        {
            vector<int> result;
            
            if(!root) return result;
            
            queue<TreeNode*> q;
            q.push(root);
            
            while( !q.empty() )
            {
                int qsize = q.size();
                result.push_back(q.front()->val);
                
                while(qsize--)
                {
                    TreeNode *node = q.front();
                    q.pop();
                    
                    if(node->right) q.push(node->right);
                    if(node->left)  q.push(node->left);
                }
            }
            
            return result;
        }
    };

Log in to reply
 

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