题目描述:从上往下打印出二叉树的每个节点,同层节点从左至右打印。

思路:利用队列实现

ac代码:

 1 import java.util.ArrayList;
 2 /**
 3 public class TreeNode {
 4     int val = 0;
 5     TreeNode left = null;
 6     TreeNode right = null;
 7 
 8     public TreeNode(int val) {
 9         this.val = val;
10          
11     }
12 
13 }
14 */
15 public class Solution {
16     public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
17         if(root==null)
18             return new ArrayList<Integer>();
19         TreeNode p;
20         ArrayList<TreeNode>list=new ArrayList<TreeNode>();
21         ArrayList<Integer>list2=new ArrayList<Integer>();
22         list.add(root);
23         for(int i=0;i<list.size();i++){
24             p=list.get(i);
25             list2.add(p.val);
26             if(p.left!=null){
27                 list.add(p.left);
28             }
29             if(p.right!=null){
30                 list.add(p.right);
31             }
32         }
33         return list2;
34     }
35 }

 

 posted on 2018-04-11 16:19  几缕清风依旧  阅读(92)  评论(0编辑  收藏  举报