share my java solution!


  • 0
    T
    class Solution {
        int sum=0;
        public int pathSum(int[] nums) {
            if(nums == null || nums.length<1){
                return 0;
            }
            Map<Integer,Integer> map = new HashMap<>();
            for(int i=0;i<nums.length;i++){
                map.put(nums[i]/10,nums[i]%10);
            }
            
            traverse(map,nums[0]/10,0);
            return sum;
        }
        
        public void traverse(Map<Integer,Integer> map,int current_pos,int pre_sum){
            int level = current_pos/10;
            int pos = current_pos%10;
            int left = (level+1)*10+(2*pos-1);
            int right = (level+1)*10 + (2*pos);
            
            if(!map.containsKey(left)&&!map.containsKey(right)){
                sum+=pre_sum+map.get(current_pos);
                return;
            }
            
            if(map.containsKey(left)){
                traverse(map,left,pre_sum+map.get(current_pos));
            }
            if(map.containsKey(right)){
                traverse(map,right,pre_sum+map.get(current_pos));
            }
        }
    }
    
    

Log in to reply
 

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