这就是一个层序遍历二叉树的问题,牛客竟然将其列为困难,可见牛客OJ是有多敷衍=_=、、
而且面向接口编程,Java的程序模板的返回值应该是List<Integer>
而不是具体实现ArrayList<Integer>
。
import java.util.*; public class Solution { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> ret = new ArrayList<>(); if (root == null) { return ret; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()) { root = queue.poll(); ret.add(root.val); if (root.left != null) { queue.offer(root.left); } if (root.right != null) { queue.offer(root.right); } } return ret; } }