题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
此题实际上与上面一题是重复了,总体还是层序遍历的思路,只不过现在不需要在打印每一行之前对打印顺序进行判断了,所以可以在前面一题的代码进行简单的修改就可以实现题目的要求了。不多说,直接看代码(已被牛客AC):
package com.rhwayfun.offer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class PrintBiTreeFromTopToBottom2 {
static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>();
if (pRoot == null) return resultList;
// 创建一个队列保存遍历的顺序
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(pRoot);
// 创建每一行遍历的结果
ArrayList<Integer> result = new ArrayList<Integer>();
int begin = 0,end = 1;
while(!queue.isEmpty()){
TreeNode curNode = queue.poll();
result.add(curNode.val);
begin++;
if(curNode.left != null) queue.add(curNode.left);
if(curNode.right != null) queue.add(curNode.right);
//判断一行的所有元素是否都添加到result中
if(begin == end){
resultList.add(result);
end = queue.size();
begin = 0;
//一行打印完毕之后,需要创建的result集合保存下一行遍历的元素
result = new ArrayList<Integer>();
}
}
return resultList;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(8);
TreeNode node1 = new TreeNode(6);
TreeNode node2 = new TreeNode(10);
TreeNode node3 = new TreeNode(5);
TreeNode node4 = new TreeNode(7);
TreeNode node5 = new TreeNode(9);
TreeNode node6 = new TreeNode(11);
root.left = node1;
root.right = node2;
node1.left = node3;
node1.right = node4;
node2.left = node5;
node2.right = node6;
ArrayList<ArrayList<Integer>> list = new PrintBiTreeFromTopToBottom2().Print(root);
for (ArrayList<Integer> arrayList : list) {
System.out.println(arrayList);
}
/*ArrayList<Integer> list = new PrintBiTreeFromTopToBottom2()
.PrintFromTopToBottom(root);
System.out.println();
for (Integer integer : list) {
System.out.println(integer + " ");
}*/
}
}
时间: 2024-09-09 23:43:51