题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
1 import java.util.ArrayList; 2 3 /* 4 * 题目描述 5 * 从上往下打印出二叉树的每个节点,同层节点从左至右打印。 6 */ 7 8 public class Main22 { 9 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 13 } 14 15 public class TreeNode { 16 int val = 0; 17 TreeNode left = null; 18 TreeNode right = null; 19 20 public TreeNode(int val) { 21 this.val = val; 22 } 23 } 24 25 public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { 26 ArrayList<Integer> array = new ArrayList<Integer>(); 27 ArrayList<TreeNode> treeArray = new ArrayList<TreeNode>(); 28 if (root == null) { 29 return array; 30 } 31 treeArray.add(root); 32 for (int i=0;i<treeArray.size();i++) { 33 TreeNode head = treeArray.get(i); 34 if (head.left != null) { 35 treeArray.add(head.left); 36 } 37 if (head.right != null) { 38 treeArray.add(head.right); 39 } 40 array.add(head.val); 41 } 42 return array; 43 } 44 45 }