从上往下打印出二叉树的每个节点,同层节点从左至右打印。
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/**
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 (null == root) return list;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (queue.size() != 0) {
TreeNode tmp = queue.poll();
list.add(tmp.val);
if (null != tmp.left) {
queue.add(tmp.left);
}
if (null != tmp.right) {
queue.add(tmp.right);
}
}
return list;
}
}