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> list = new ArrayList<Integer>(); if(root==null){ return list; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); //放入队列 queue.offer(root); //当队列不为空 while(!queue.isEmpty()){ TreeNode treeNode = queue.poll(); //如果左节点不为空,左节点放入队列 if(treeNode.left != null){ queue.offer(treeNode.left); } //如果右节点不为空,把右节点放入队列 if(treeNode.right != null){ queue.offer(treeNode.right); } list.add(treeNode.val); } return list; } }
时间: 2024-10-05 07:37:18