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] ]
https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/
思路:还是层序遍历的思路,用queeu做,插入null分层。返回时Collection.reverse一下。
public class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if (root == null) return res; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); queue.add(null); List<Integer> tmp = new ArrayList<Integer>(); while (!queue.isEmpty()) { TreeNode node = queue.remove(); if (node == null) { res.add(new ArrayList<Integer>(tmp)); tmp.clear(); if (!queue.isEmpty()) queue.add(null); } else { // System.out.println(node.val); tmp.add(node.val); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } } Collections.reverse(res); return res; } public static void main(String[] args) { TreeNode root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.right.left = new TreeNode(15); root.right.right = new TreeNode(7); System.out.println(new Solution().levelOrderBottom(root)); } }
参考: