title: '算法:从上往下打印二叉树' cover: https://img.paulzzh.com/touhou/random?31 categories: 算法题目 date: 1996-07-27 08:00:00 toc: true
<br/>
<!--more-->从上往下打印出二叉树的每个节点,同层节点从左至右打印。
简单的二叉树的BFS
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>(256);
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
res.add(cur.val);
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
}
return res;
}
}