题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
利用队列FIFO特性
创建一个队列,然后依次添加左、右子节点。从队列中取的时候,就相当于在每一层从左到右的取节点
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
if(root==null)
return list;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
root = queue.poll();
if(root.left!=null){
queue.offer(root.left);
}
if(root.right!=null){
queue.offer(root.right);
}
list.add(root.val);
}
return list;
}
}