Skip to content

Commit 14b3e0e

Browse files
committed
C# depth sum recursive
1 parent 48dadec commit 14b3e0e

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

consoleApp/consoleApp/DepthSum.cs

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
using System;
2+
namespace consoleApp
3+
{
4+
public class DepthSum
5+
{
6+
public DepthSum()
7+
{
8+
}
9+
10+
/**
11+
* Given a nested list of integers, returns the sum of all integers in the list weighted by their depth
12+
* For example, given the list {{1,1},2,{1,1}} the function should return 10 (four 1's at depth 2, one 2 at depth 1)
13+
* Given the list {1,{4,{6}}} the function should return 27 (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3)
14+
*/
15+
public int depthSum (List<NestedInteger> input)
16+
{
17+
//Implementation here
18+
19+
int level= 1;
20+
depthSum(input, level);
21+
22+
}
23+
24+
//O(n)? n -> 2^n
25+
public int depthSum(List<NestedInteger> input, int level){
26+
int sum = 0;
27+
++level;
28+
for(NestedInteger i: input){
29+
if(i.isInteger()){
30+
sum += (i*level);
31+
}else{
32+
sum+= depthSum(i, level);
33+
34+
}
35+
}
36+
return sum;
37+
38+
}
39+
/**
40+
* This is the interface that represents nested lists.
41+
* You should not implement it, or speculate about its implementation.
42+
*/
43+
public interface NestedInteger
44+
{
45+
/** @return true if this NestedInteger holds a single integer, rather than a nested list */
46+
boolean isInteger();
47+
48+
/** @return the single integer that this NestedInteger holds, if it holds a single integer
49+
* Return null if this NestedInteger holds a nested list */
50+
Integer getInteger();
51+
52+
/** @return the nested list that this NestedInteger holds, if it holds a nested list
53+
* Return null if this NestedInteger holds a single integer */
54+
List<NestedInteger> getList();
55+
}
56+
57+
}
58+
}

consoleApp/consoleApp/consoleApp.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
<Compile Include="Extensions.cs" />
3838
<Compile Include="Status.cs" />
3939
<Compile Include="MySort.cs" />
40+
<Compile Include="DepthSum.cs" />
4041
</ItemGroup>
4142
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
4243
</Project>

0 commit comments

Comments
 (0)