題目描述
從上往下列印出二叉樹的每個節點,同層節點從左至右列印。
題目解答
import java.util.ArrayList; import java.util.Queue; 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) { ArrayList<Integer> res=new ArrayList<>(); if(root==null){ return res; } Queue<TreeNode> queue=new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ TreeNode node=queue.poll(); res.add(node.val); if(node.left!=null){ queue.offer(node.left); } if(node.right!=null){ queue.offer(node.right); } } return res; } }