二叉树的层次遍历就是从上到下,从左到右遍历,也就是广度优先遍历。
二叉树的层次遍历,用队列实现,先将根节点入队列,只要队列不为空,然后出队,并访问,接着让节点的左右子树依次入队。
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();//新建一个列表,用于存储数值
if (root == null) return list;
Queue<TreeNode> queue = new LinkedList<TreeNode>();//新建一个队列,用于存储节点
queue.offer(root);//根节点入队
while (!queue.isEmpty()) {
TreeNode current = queue.poll();//出队
list.add(current.val);
if (current.left != null) queue.offer(current.left);//如果左子树存在,左子树入队
if (current.right != null) queue.offer(current.right);//如果右子树存在,右子树入队
}
return list;
}
用队列实现是解此题的关键