my solution with level traversal


  • 0
    L

    As the problem has described, we can have draw conclusion that the right side view is the last node of one level traversal from left to right.
    So we can get the right side view node when one level is over.
    Codes details are as following:

     vector<int> rightSideView(TreeNode* root) {
            queue<TreeNode*> levelqueue;
            vector<int> rightpath;
            if(!root)
                return rightpath;
            levelqueue.push(root);
           /**level1 stands for the number of current level nodes 
              level2 stands for the number of next level nodes.
          */
            int level1=1,level2=0;
            TreeNode* proot;
            while(!levelqueue.empty()){
                proot = levelqueue.front();
                levelqueue.pop();
                if(proot->left){
                    levelqueue.push(proot->left);
                    level2++;
                }
                if(proot->right){
                    levelqueue.push(proot->right);
                    level2++;
                }
                
                if(--level1 == 0){//end for one level and should start next level 
                    rightpath.push_back(proot->val);//right side view of one level
                    level1 = level2;
                    level2 = 0;
                }
            }
            return rightpath;
        }
    

Log in to reply
 

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