Java solution using recursion and iterative approach


  • 0
    C
        public int depthSum(List<NestedInteger> nestedList) {
            return findSum(nestedList, 1);
        }
        
        private int findSum(List<NestedInteger> nestedList, int depth){
            int sum = 0;
            for(NestedInteger nestedInteger : nestedList){
                if(nestedInteger.isInteger()){
                    sum += (depth * nestedInteger.getInteger());
                }
                else{
                    sum += findSum(nestedInteger.getList(), depth + 1);
                }
            }
            
            return sum;
        }
    

    Iterative approach

    	public int depthSum(List<NestedInteger> nestedList) {
    		Stack<Pair> stack = new Stack<Pair>();
    		stack.push(new Pair(nestedList, 1));
    		int sum = 0;
    		while (!stack.isEmpty()) {
    			Pair top = stack.pop();
    			for (NestedInteger nestedInteger : top.nestedList) {
    				if (nestedInteger.isInteger()) {
    					sum += (top.depth * nestedInteger.getInteger());
    				} else {
    					stack.push(new Pair(nestedInteger.getList(), top.depth + 1));
    				}
    			}
    		}
    
    		return sum;
    	}
    
    	private static class Pair {
    		List<NestedInteger> nestedList;
    		int depth;
    
    		public Pair(List<NestedInteger> nestedList, int depth) {
    			this.nestedList = nestedList;
    			this.depth = depth;
    		}
    	}
    

Log in to reply
 

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