Question
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
Solution
Same method as "Binary Tree Level Order Traversal". Note that for ArrayList, it has function add(int index, E element).
1 /** 2 * Definition for a binary tree node. 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<Integer>> levelOrderBottom(TreeNode root) { 12 List<List<Integer>> result = new ArrayList<List<Integer>>(); 13 if (root == null) 14 return result; 15 Deque<TreeNode> prev = new ArrayDeque<TreeNode>(); 16 Deque<TreeNode> current; 17 TreeNode tmpNode; 18 prev.addLast(root); 19 while (prev.size() > 0) { 20 current = new ArrayDeque<TreeNode>(); 21 List<Integer> tmpList = new ArrayList<Integer>(); 22 while (prev.size() > 0) { 23 tmpNode = prev.pop(); 24 if (tmpNode.left != null) 25 current.addLast(tmpNode.left); 26 if (tmpNode.right != null) 27 current.addLast(tmpNode.right); 28 tmpList.add(tmpNode.val); 29 } 30 prev = current; 31 result.add(0, tmpList); 32 } 33 return result; 34 } 35 }