LeetCode429

    技术2022-07-29  84

    /* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ class Solution { public List<List<Integer>> levelOrder(Node root) { //建立结果数组 List<List<Integer>> ans = new ArrayList<>(); while(root == null){ return ans; } //建立队列 Queue<Node> q = new LinkedList<>(); //根节点入队列 q.add(root); while(!q.isEmpty()){ List<Integer> tem = new ArrayList<>(); int size = q.size(); for(int i = 0;i < size;i++){ Node cur = q.poll(); if(cur == null) continue; tem.add(cur.val); //建立孩子列表 List<Node> children = cur.children; for(Node child : children){ if(child != null){ q.add(child); } } } ans.add(tem); } return ans; } }

     

    Processed: 0.014, SQL: 9