层序遍历二叉树

 1 package com.algorithm;
 2 
 3 import java.util.ArrayList;
 4 import java.util.LinkedList;
 5 import java.util.Queue;
 6 
 7 //从上往下打印出二叉树的每个节点,同层节点从左至右打印。
 8 /**
 9 public class TreeNode {
10     int val = 0;
11     TreeNode left = null;
12     TreeNode right = null;
13 
14     public TreeNode(int val) {
15         this.val = val;
16     }
17 }
18 */
19 public class PrintBinaryTree {
20     //思路 ,队列
21      public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
22          ArrayList<Integer> ls = new ArrayList<Integer>();
23          if(root == null)
24              return ls;
25          Queue<TreeNode> queue = new LinkedList<TreeNode>();
26          queue.offer(root);//入队
27          while(!queue.isEmpty()){
28              TreeNode tn = queue.poll();//出对
29              ls.add(tn.val);//保存值
30              if(tn.left != null)
31                  queue.offer(tn.left);//入队
32              if(tn.right != null)
33                  queue.offer(tn.right);//出对
34          }
35          return ls;
36       }
37 }

 

posted @ 2017-03-10 14:32  fankongkong  阅读(137)  评论(0编辑  收藏  举报