C++ self explanatory code


  • 0
    G
    class Solution {
    public:
        int pathSum(vector<int>& nums) {
           
            unordered_map<int,int> map;
            
            for(auto & i : nums){
                map[i/10] = i % 10;
            }
            
            return getPathSum(11,map,0);
        }
        
        int getPathSum(int root, unordered_map<int,int> &m,int parent){
            
            if(m.find(root) == m.end()){
                return 0;
            }
            
            int level = root/10;
            int loc = root% 10;
            int leftRoot = (level + 1)*10 + (loc*2) - 1;
            int rightRoot = (level+ 1)*10 + (loc*2);
            
            if(m.find(leftRoot) == m.end() && m.find(rightRoot) == m.end()){
                return parent + m[root];
            }
            
            int left = 0, right =0 ;
            
            if(m.find(leftRoot) != m.end()){
                left = getPathSum(leftRoot,m,parent + m[root]);
            }
            
            if(m.find(rightRoot) != m.end()){
                right = getPathSum(rightRoot,m,parent + m[root]);
            }
          
            return left + right;
        }  
    };
    

Log in to reply
 

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