标签:item list sub rom code des ISE scribe color
22. 从上往下打印二叉树
层序遍历二叉树即可
1 import java.util.ArrayList; 2 import java.util.Queue; 3 import java.util.LinkedList; 4 public class Solution { 5 // 层序遍历二叉树即可 6 public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { 7 Queue<TreeNode> Q = new LinkedList<>(); 8 ArrayList<Integer> list = new ArrayList<>(); 9 if(root == null){ 10 return list; 11 } 12 Q.offer(root); 13 TreeNode top; 14 while(!Q.isEmpty()){ 15 // 访问队首元素 16 top = Q.poll(); 17 list.add(top.val); 18 if(top.left != null) 19 Q.offer(top.left); 20 if(top.right != null) 21 Q.offer(top.right); 22 } 23 return list; 24 } 25 }
标签:item list sub rom code des ISE scribe color
原文地址:https://www.cnblogs.com/hi3254014978/p/12357485.html