18-line recursive C++ solution in 7 ms


  • 6
    K
    class Solution {
        int level = 0;//number of numbers that have been "seen".
        vector<int> answer;
    public:
        vector<int> rightSideView(TreeNode *root) {
            if (root!=NULL) travDown(root,0);
            return answer;
        }
        void travDown(TreeNode* nd, int N){//travel down, always go right first
            if (N>=level) {
                answer.push_back(nd->val);
                level++;
            }
            ++N;
            if (nd->right!=NULL) travDown(nd->right,N);
            if (nd->left!=NULL) travDown(nd->left,N);
        }
    };

  • 0
    K

    Should add the following two lines for initialization if the code is to be repeatedly run:

    level = 0;
    answer.clear();


Log in to reply
 

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