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]
,
3 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
题目含义:这道题的要求是从下往上分层遍历二叉树。
1 public List<List<Integer>> levelOrderBottom(TreeNode root) { 2 List<List<Integer>> result = new LinkedList<List<Integer>>(); 3 Queue<TreeNode> queue = new LinkedList<>(); 4 if (root == null) return result; 5 queue.add(root); 6 while (!queue.isEmpty()) { 7 int size = queue.size(); 8 List<Integer> values = new ArrayList<>(); 9 for (int i = 0; i < size; i++) { 10 TreeNode node = queue.poll(); 11 if (node.left != null) queue.offer(node.left); 12 if (node.right != null) queue.offer(node.right); 13 values.add(node.val); 14 } 15 result.add(0, values); 16 } 17 return result; 18 }