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] ]
和上一题类似,树的层次遍历。不同的是需要将元素逆序转换一下。public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> list = new ArrayList<List<Integer>>(); if (root == null) { return list; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int count = 1; while (!queue.isEmpty()) { int len = count; count = 0; List<Integer> subList = new ArrayList<Integer>(); for(int i = 0; i < len; i++) { TreeNode curNode = queue.poll(); subList.add(curNode.val); if (curNode.left != null) { queue.offer(curNode.left); count++; } if (curNode.right != null) { queue.offer(curNode.right); count++; } } list.add(subList); } List<List<Integer>> result = new ArrayList<List<Integer>>(); for (int i = list.size(); i > 0; i--) { result.add(list.get(i - 1)); } return result; }
Binary Tree Level Order Traversal II,布布扣,bubuko.com
Binary Tree Level Order Traversal II
原文地址:http://blog.csdn.net/u010378705/article/details/28621053