二刷339. Nested List Weight Sum

Easy
一刷恰好在两个月前,第二次写还是没防备地写出了helper method传参传了int type这种错误. However提交报错后很快反应过来了,自己还是写出来了。
之后尽量别写出类似于这样的传参传int, string相等写==,treeNode相等不知道用== 这些比较低级的错误了.

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
public class Solution {
    public int depthSum(List<NestedInteger> nestedList) {
        int sum = 0;
        dfsHelper(nestedList, 1);
        return sum;
    }
    private void dfsHelper(List<NestedInteger> nestedList, int level){
         for (NestedInteger ni : nestedList){
            if (ni.isInteger()){
                sum += ni.getInteger() * level;
            } else {
                dfsHelper(ni.getList(), level + 1);
            }
        }
    } 
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/863bc22f510a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞