C# recursive solution


  • 0
    J
    public int DepthSumInverse(IList<NestedInteger> nestedList) 
        {
            if (nestedList.Count == 0) return 0;
            var depth = 1;
            foreach (var child in nestedList)
            {
                if (!child.IsInteger())
                {
                    depth = Math.Max(depth, Depth(child));
                }
            }
            //depth++;
            var sum = 0;
            
            foreach (var child in nestedList)
            {
                if (child.IsInteger())
                {
                    sum = sum + (child.GetInteger()*depth);
                }
                else
                {
                    sum = sum + GetSum(child, depth-1);
                }
            }
            return sum;
            
        }
        
        private int GetSum(NestedInteger n, int depth)
        {
            var sum = 0;
            if (n.GetList() == null) return 0;
            foreach (var child in n.GetList())
            {
                if (child.IsInteger())
                {
                    sum = sum + (child.GetInteger()*depth);
                }
                else
                {
                    sum = sum + GetSum(child, depth-1);
                }
            }
            return sum;
        }
        
        private int Depth(NestedInteger n)
        {
            if (n.IsInteger()) return 1;
            if (n.GetList() == null) return 0;
            var max = 0;
            foreach (var child in n.GetList())
            {
                max = Math.Max(max, Depth(child));
            }
            return max+1;
        }
    

Log in to reply
 

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