搬了实验室,好多天没写博客了今天就多写几个。
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
分析:从题意很明显是树的层次遍历,树层次遍历的大体思想是引入一个先入先出的队列,如果根节点不为空,根节点入队,如果队列不为空,将队首节点的左子节点和右子节点分别入队。访问队首节点,队首节点出队。代码如下所示:
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 Queue<TreeNode> qe =
new LinkedList();
20 ArrayList<Integer> result =
new ArrayList<Integer>
();
21 if(root ==
null){
22 return result;
23 }
24 qe.offer(root);
25
26 TreeNode tmp =
null;
27 while(qe.isEmpty()!=
true){
28 tmp =
qe.poll();
29 result.add(tmp.val);
30 if(tmp.left!=
null){
31 qe.offer(tmp.left);
32 }
33 if(tmp.right!=
null){
34 qe.offer(tmp.right);
35 }
36 }
37
38 return result;
39 }
40 }
转载于:https://www.cnblogs.com/huntertoung/p/4800915.html