Find depth(Q104 MaxDepth of Binary Tree);Find Sum(Q339 NestedList Weight Sum)


  • 0
     public class Solution {
    public int depthSumInverse(List<NestedInteger> nestedList) {
        int level=computeHeight(nestedList);
        return computeSum(nestedList,level);
    }
    
    public int computeHeight(List<NestedInteger> nestedList){
        int height=1;
        for(int i=0;i<nestedList.size();i++){
            if(!nestedList.get(i).isInteger()){
                height=Math.max(height,computeHeight(nestedList.get(i).getList())+1);
            }
        }
        return height;
    }
    
    public int computeSum(List<NestedInteger> list,int level){
        int sum=0;
        for(int i=0;i<list.size();i++){
            if(list.get(i).isInteger()){
                sum+=list.get(i).getInteger()*level;
            }else{
                sum+=computeSum(list.get(i).getList(),level-1);
            }
        }
        
        return sum;
    }
    

    }


Log in to reply
 

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