从上往下打印二叉树
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&&tqId=11175&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
这就是一个层序遍历二叉树的问题,牛客竟然将其列为困难,可见牛客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;
}
} 
查看14道真题和解析
