题目
思路
正常层序遍历输出: [[3],[9,20],[15,7]]
这道题要求的输出:[[15,7],[9,20],[3]]
可以观察到,只要我们把原来的结果reverse一下就行了。
代码
//leetcode submit region begin(Prohibit modification and deletion)import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<List<Integer>> levelOrderBottom(TreeNode root) {//创建一个辅助队列,存放节点Queue<TreeNode> queue = new LinkedList<TreeNode>();//创建一个结果ListList<List<Integer>> res = new ArrayList<>();if (root == null) {return res;}queue.add(root);while (!queue.isEmpty()) {int len = queue.size();List<Integer> item = new ArrayList<>();while (len > 0) {TreeNode temp = queue.poll();item.add(temp.val);if (temp.left != null)queue.add(temp.left);if (temp.right != null)queue.add(temp.right);len--;}res.add(item);}Collections.reverse(res);return res;}
}
//leetcode submit region end(Prohibit modification and deletion)