从上往下打印二叉树
2019-03-01 22:29 YihangZhou 阅读(108) 评论(0) 编辑 收藏 举报题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
import java.util.ArrayList; import java.util.Collections; /** 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<TreeNode> queue = new ArrayList<TreeNode>(); ArrayList<Integer> list = new ArrayList<>(); if(root==null)return list; queue.add(root); while(!queue.isEmpty()) { TreeNode temp = queue.remove(0); list.add(temp.val); if(temp.left!=null)queue.add(temp.left); if(temp.right!=null)queue.add(temp.right); } return list; } }