Simple C++ using depth list


  • 0
    C

    Create a list of nodes for each depth of the tree using preorder traversal, and return the vector comprised of the last node added at each depth.

    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
    
            vector<int> result;
            
            vector<vector<int>> nodeListPerDepth;
            depthList(root, nodeListPerDepth, 0);
            
            for (auto nodeList : nodeListPerDepth){
                result.push_back(*(nodeList.end()-1));
            }
            
            
            return result;
            
        }
        
        void depthList(TreeNode* node, vector<vector<int>>& list, int depth){
            
            if (!node) { return; }
            
            if (list.size() == depth){
                list.push_back(vector<int>());
            }
            list[depth].push_back(node->val);
            depthList(node->left, list, depth+1);
            depthList(node->right, list, depth+1);
        }
    };
    

Log in to reply
 

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