/**
* 从上往下打印出二叉树的每个节点,同层节点从左至右打印
*/
package javabasic.nowcoder;
import java.util.ArrayList;
import java.util.Queue;
import javax.management.Query;
class TreeNode27 {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode27(int val) {
this.val = val;
}
}
/*
* 借组一个队列辅助层次遍历二叉树
*/
public class Main27 {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> arr = new ArrayList<Integer>();
if(root==null) {
return arr;
}
Queue<TreeNode> queue = (Queue<TreeNode>) new LinkedList();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode temp = queue.poll();
if(temp.left!=null) {
queue.offer(temp.left);
}
if(temp.right!=null) {
queue.offer(temp.right);
}
arr.add(temp.val);
}
return arr;
}
}