题目
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
即对二叉树进行层次遍历
思路
把二叉树的节点存入队列
如果不为空 则把值存入Arraylist
访问后删除队列中的元素 同时保存给tmp
如果tmp的左孩子不为空 存入队列
如果又孩子不为空 存入队列
代码
import java.util.*;
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(root == null)return result;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode temp = queue.poll();
result.add(temp.val);
if(temp.left != null)queue.offer(temp.left);
if(temp.right != null)queue.offer(temp.right);
}
return result;
}
}