题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
层级遍历:队列
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> array = new ArrayList();
if (root == null) return array;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode temp = queue.poll();
array.add(temp.val);
if (temp.left != null) {
queue.add(temp.left);
}
if (temp.right != null) {
queue.add(temp.right);
}
}
return array;
}
}
网友评论