C++ Level Order Traversal Solution


  • 0
    L

    Just level order traversal and record the rightmost element. Can anyone improve this code to make it simpler?

    class Solution {
    public:
        vector<int> rightSideView(TreeNode *root) 
        {
            vector<int> res;
            vector<queue<TreeNode*>> q(2,queue<TreeNode*>());
            if(root==NULL) return res;
            int count=0;
            q[0].push(root);
            while(q[count%2].size())
            {
                TreeNode* node = q[count%2].front();
                q[count%2].pop();
                if(node->left)
                    q[(count+1)%2].push(node->left);
                if(node->right)
                    q[(count+1)%2].push(node->right);
                if(q[count%2].empty())
                {
                    res.push_back(node->val);
                    count++;
                }
            }
            return res;
        }
    
    };

Log in to reply
 

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