Three ways in C++.


  • 0
    X

    DFS recursive:

     vector<int> rightSideView(TreeNode* root) {
        vector<int> T;
        if(!root) return T;
        T.push_back(root->val);
        DFS(T, root, 1);
        return T;
    }
    
    void DFS(vector<int>& T, TreeNode* root, int layer)
    {
        if(!root) return;
        if(layer>T.size())
            T.push_back(root->val);
          DFS(T, root->right, layer+1);
          DFS(T, root->left, layer+1);
      
    }
    

    DFS nonrecursive:

     vector<int> rightSideView(TreeNode* root) {
        vector<int> T;//the answer
        if(!root) return T;
        
        stack<TreeNode*> S;
        stack<int> diff; // save each nodes' depth
        int count=0;//the maximum depth currently.
        
        T.push_back(root->val);
        diff.push(0);
        S.push(root);
        
        while(!S.empty())
        {
            TreeNode* tmp=S.top();
            int cur = diff.top();
            S.pop();
            diff.pop();
            if(tmp->left)
            {
                S.push(tmp->left);
                diff.push(cur+1);
                if(!tmp->right)
                {   
                    if((cur+1)>count)
                    {
                        T.push_back(tmp->left->val);
                        count++;
                    }
                }
            }
            
            if(tmp->right)
            {
                S.push(tmp->right);
                diff.push(cur+1);
                if((cur+1)>count)
                {
                    T.push_back(tmp->right->val);
                    count++;
                }
            }
            
        }
        return T;
    }
    

    BFS:

        vector<int> rightSideView(TreeNode* root) {
        vector<int> T;
        if(!root) return T;
        
        T.push_back(root->val);
        int layer=0;
        queue<TreeNode*> Q;
        Q.push(root);
        while(!Q.empty())
        {
            layer = Q.size();
            while(layer)
            {
                TreeNode* tmp = Q.front();
                if(tmp->right)
                {
                    Q.push(tmp->right);
                    if(layer == Q.size()-1)
                        T.push_back(tmp->right->val);
                }
                if(tmp->left)
                {
                    Q.push(tmp->left);
                    if(layer == Q.size()-1)
                        T.push_back(tmp->left->val);
                }
                Q.pop();
                layer--;
            }
        }
        return T;
    }

Log in to reply
 

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