一、题目
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
二、解法
1 import java.util.ArrayList; 2 import java.util.LinkedList; 3 import java.util.Queue; 4 /** 5 public class TreeNode { 6 int val = 0; 7 TreeNode left = null; 8 TreeNode right = null; 9 10 public TreeNode(int val) { 11 this.val = val; 12 13 } 14 15 } 16 */ 17 public class Solution { 18 public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { 19 /*ArrayList<Integer> ls = new ArrayList<Integer>(); 20 if(root == null) 21 return ls; 22 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 23 queue.offer(root);//入队 24 while(!queue.isEmpty()){ 25 TreeNode tn = queue.poll();//出对 26 ls.add(tn.val);//保存值 27 if(tn.left != null) 28 queue.offer(tn.left);//入队 29 if(tn.right != null) 30 queue.offer(tn.right);//出对 31 } 32 return ls;*/ 33 ArrayList<Integer> al = new ArrayList<Integer>(); 34 if(root == null) 35 return al; 36 Queue<TreeNode> tn = new LinkedList<TreeNode>(); 37 tn.offer(root); 38 while(!tn.isEmpty()){ 39 TreeNode tree = tn.poll(); 40 al.add(tree.val); 41 if(tree.left != null) 42 tn.offer(tree.left); 43 if(tree.right != null) 44 tn.offer(tree.right); 45 } 46 return al; 47 } 48 }
时间: 2024-10-23 09:42:59