题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印;ps.就是层次遍历
解题思路
用队列(LinkedList)来进行层次遍历;
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (root == null) {
return list; //如果根节点为空,就直接返回空的List
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); //队列
queue.add(root); //添加根节点
while (!queue.isEmpty()){
TreeNode current = queue.pop();
list.add(current.val);
if (current.left != null){
queue.add(current.left); //把左节点加入队列
}
if (current.right != null){
queue.add(current.right); //把右节点加入队列
}
}
return list;
}