从上往下打印二叉树
题目描述:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
实现语言:Java
import java.util.ArrayList; import java.util.LinkedList; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { LinkedList<TreeNode> que=new LinkedList<TreeNode>(); ArrayList<Integer> res=new ArrayList<Integer>(); if(root==null){ return res; } que.offer(root); while(!que.isEmpty()){ root=que.poll(); res.add(root.val); if(root.left!=null){ que.offer(root.left); } if(root.right!=null){ que.offer(root.right); } } return res; } }