import java.util.ArrayList; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
} */ //借助队列特性完成树的层序遍历,顺便将输出节点值 import java.util.LinkedList; public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> arr = new ArrayList<Integer>();//用来存储遍历后的结果
LinkedList<TreeNode> list = new LinkedList<TreeNode>();//用来作层次遍历
TreeNode temp = null;
if(root == null){
return arr;
}
list.add(root);
while(!list.isEmpty()){
temp = list.poll();
if(temp.left != null){
list.add(temp.left);
}
if(temp.right != null){
list.add(temp.right);
}
arr.add(temp.val);
}
return arr;
//
}
}