题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
思路:层次遍历,用arraylist模拟一个队列来存储相应的TreeNode
*/
import java.util.LinkedList;
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
//注意不能直接返回null,不然树为空时,不能通过
if(root ==null) return new ArrayList<Integer>();
//1、定义一个Arraylist对象来存储二叉树的节点值
ArrayList<Integer> arr = new ArrayList<>();
//2、用linkedList来做层次遍历
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root);
while(!list.isEmpty()){
TreeNode temp = list.removeFirst();
if(temp.left!=null){
list.add(temp.left);
}
if(temp.right!=null){
list.add(temp.right);
}
arr.add(temp.val);
}
return arr;
}
}