题解 | #从下到上打印二叉树#
从下到上打印二叉树
https://www.nowcoder.com/practice/ed982e032ff04d6a857b4cb4e6369d04
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型二维数组 */ List<List<Integer>> res = new ArrayList<>(); public int[][] levelOrderBottom (TreeNode root) { // write code here Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while(!q.isEmpty()) { int sz = q.size(); List<Integer> temp = new ArrayList<>(); for(int i = 0; i < sz; i++) { TreeNode node = q.poll(); temp.add(node.val); if(node.left != null) q.offer(node.left); if(node.right != null) q.offer(node.right); } res.add(temp); } Collections.reverse(res); // for(List<Integer> temp : res) { // for(int x : temp) { // System.out.println(x); // } // } int[][] result = new int[res.size()][]; for(int i = 0; i < result.length; i++) { int[] temp = new int[res.get(i).size()]; for(int j = 0; j < res.get(i).size(); j++) { temp[j] = res.get(i).get(j); } result[i] = temp; } return result; } }