题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
import java.util.*; import java.util.ArrayList; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> tree = new ArrayList(); if(root == null){ return tree;//注意:空树返回一个默认构造的空ArrayList,而不是一个空指针nul //return null 会出现空指针异常 } //建立临时队列来存储 Queue<TreeNode> q = new ArrayDeque<TreeNode>(); q.offer(root); while(!q.isEmpty()){ TreeNode cur = q.poll(); tree.add(cur.val); if(cur.left!=null){ q.add(cur.left); } if(cur.right!=null){ q.add(cur.right); } } return tree; } }