- Binary Tree Level Order Traversal II
Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
1. 3
2. / \
3. 9 20
4. / \
5. 15 7
return its bottom-up level order traversal as:
1. [
2. [15,7],
3. [9,20],
4. [3]
5. ]
Solution:
1. /*
2. * Definition for binary tree
3. * public class TreeNode {
4. * int val;
5. * TreeNode left;
6. * TreeNode right;
7. * TreeNode(int x) { val = x; }
8. * }
9. /
10. public class Solution {
11. public List<List
12. List<List
13. List
14. 15. if (root == null) {
16. return res;
17. }
18. 19. Queue
20. Queue
21. 22. curr.add(root);
23. 24. while (!curr.isEmpty()) {
25. TreeNode node = curr.poll();
26. list.add(node.val);
27. 28. if (node.left != null) {
29. next.add(node.left);
30. }
31. 32. if (node.right != null) {
33. next.add(node.right);
34. }
35. 36. if (curr.isEmpty()) {
37. res.add(0, list);
38. list = new ArrayList
39. 40. curr = next;
41. next = new LinkedList
42. }
43. }
44. 45. return res;
46. }
47. }
