Share DFS and BFS solution both 2ms


  • 0
    2

    DFS

    public class Solution {
        public int depthSum(List<NestedInteger> nestedList) {
            return dfs(nestedList, 1);
        }
        private int dfs(List<NestedInteger> list, int level) {
            int res = 0;
            for (NestedInteger ni : list) {
                if (ni.isInteger()) {
                    res += (ni.getInteger() * level);
                } else {
                    res += dfs(ni.getList(), level + 1);
                }
            }
            return res;
        }
    }
    

    BFS

    public class Solution {
        public int depthSum(List<NestedInteger> p) {
            int res = 0;
            if (p == null || p.size() == 0) {
                return res;
            }
            int level = 1;
            LinkedList<List<NestedInteger>> queue = new LinkedList<>();
            queue.offer(p);
            while (!queue.isEmpty()) {
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    List<NestedInteger> li = queue.poll();
                    for (NestedInteger ni : li) {
                        if (ni.isInteger()) {
                            res += (ni.getInteger() * level);
                        } else {
                            queue.offer(ni.getList());
                        }
                    }
                }
                level++;
            }
            return res;
        }
    }
    

    Try not to shorten the code for better readability.


Log in to reply
 

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