Guest User

Untitled

a guest
Jul 20th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. //BFS solution
  2. //Time: O(n), 6ms
  3. //Space: O(n)
  4. class Solution {
  5. public List<List<Integer>> levelOrder(Node root) {
  6. List<List<Integer>> ans = new ArrayList<>();
  7. if(root == null) return ans;
  8. Queue<Node> q = new LinkedList<>();
  9. q.offer(root);
  10. while(!q.isEmpty()) {
  11. int size = q.size();
  12. List<Integer> list = new ArrayList<>();
  13. for(int i = 0; i < size; i++) {
  14. Node node = q.poll();
  15. list.add(node.val);
  16. for(Node child : node.children) {
  17. q.offer(child);
  18. }
  19. }
  20. ans.add(list);
  21. }
  22. return ans;
  23. }
  24. }
  25. /*
  26. // Definition for a Node.
  27. class Node {
  28. public int val;
  29. public List<Node> children;
  30.  
  31. public Node() {}
  32.  
  33. public Node(int _val,List<Node> _children) {
  34. val = _val;
  35. children = _children;
  36. }
  37. };
  38. */
Add Comment
Please, Sign In to add comment