从上往下打印二叉树

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

思路:就是写一个层序遍历代码,用队列将根、左孩子、右孩子有序入队最后再出队即可

 1 import java.util.*;
 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     
17     Queue<TreeNode> queue = new LinkedList<>();
18     ArrayList<Integer> arr = new ArrayList();
19     
20     public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
21         
22         if(root==null)
23             return arr;
24         queue.add(root);
25         while(!queue.isEmpty()){
26             TreeNode t = queue.poll();//好久没用过队列函数不太清楚了!!!
27             arr.add(t.val);
28             if(t.left!=null)
29                 queue.add(t.left);
30             if(t.right!=null)
31                 queue.add(t.right);
32         }
33         return arr;
34     }
35 }

代码一天不敲就生疏(ps:每天都敲也菜。。。。。)

原文地址:https://www.cnblogs.com/haq123/p/12189786.html