1.简述:
给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即从叶节点所在层到根节点所在层,从左到右逐层遍历)
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[15,7],[9,20],[3]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
2.实现代码:
class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> levelOrder = new LinkedList<List<Integer>>(); if (root == null) { return levelOrder; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { List<Integer> level = new ArrayList<Integer>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); level.add(node.val); TreeNode left = node.left, right = node.right; if (left != null) { queue.offer(left); } if (right != null) { queue.offer(right); } } levelOrder.add(0, level); } return levelOrder; }}