Solution in C++


  • 0
    S
    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            vector<int> arr;
            if(root) 
                arr.push_back(root->val);
            else
                return vector<int> {};
            deque<TreeNode*> que;
            que.push_back(root);
            int count = 1;
            int val = 0;
            int numAtLevel = 0;
            while(que.size()){
    
                TreeNode* node = que.front();
                que.pop_front();
                count --;
                
                if(node->left){
                    que.push_back(node->left);
                    val = node->left->val;
                    numAtLevel += 1;
                }
                if(node->right){
                    que.push_back(node->right);
                    val = node->right->val;
                    numAtLevel += 1;
                }
                
                if(count == 0){
                    if(numAtLevel == 0)
                        return arr;
                    arr.push_back(val);
                    count = numAtLevel;
                    numAtLevel = 0;
                }
            }
            return arr;
        }
    };
    

Log in to reply
 

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