Guest User

Untitled

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