C++ DFS O(n) 8ms with explanation


  • 1
    C

    class Solution {
    public:
    vector<int> valuelist;
    vector<int> rightSideView(TreeNode *root) {
    if (root==NULL) return valuelist;
    gettherightmostvalue(root,0);
    return valuelist;
    }

    void gettherightmostvalue(TreeNode *root,int depth)
    {
        if (root==NULL) return ;
        if (valuelist.size()<depth+1)
        valuelist.push_back(root->val);
        else
        valuelist[depth]=root->val;
        gettherightmostvalue(root->left,depth+1);
        gettherightmostvalue(root->right,depth+1);
    }
    

    };
    explanation:
    valuelist store the node value we view last time.
    so,the value in valuelist is the rightmost node view


Log in to reply
 

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