题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
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 { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { //使用层序遍历 Queue<TreeNode> queue = new ArrayDeque<>(); ArrayList<Integer> list = new ArrayList<>(); if (root == null) { return list; } //层序遍历结果加入list queue.add(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode tmp = queue.poll(); list.add(tmp.val); if (tmp.left != null) { queue.add(tmp.left); } if (tmp.right != null) { queue.add(tmp.right); } } } return list; } }