剑指Offer_22 发表于 2017-12-03 | 分类于 剑指Offer 题目从上往下打印出二叉树的每个节点,同层节点从左至右打印。 解题思路层序遍历二叉树 将ArrayList换成LinkedList效率会高一点…… 123456789101112131415161718192021222324252627282930313233343536import java.util.ArrayList;/**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> ret = new ArrayList<>(); ArrayList<TreeNode> nodeList = new ArrayList<>(); if(root == null){ return ret; } nodeList.add(root); while(!nodeList.isEmpty()){ TreeNode node = nodeList.get(0); nodeList.remove(0); ret.add(node.val); if(node.left != null){ nodeList.add(node.left); } if(node.right != null){ nodeList.add(node.right); } } return ret; }}