P32_1:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
if (root == null)
return list;
Queue<TreeNode> que = new LinkedList<>();
que.add(root);
while (!que.isEmpty()) {
TreeNode item = que.poll();
list.add(item.val);
if (item.left != null)
que.add(item.left);
if (item.right != null)
que.add(item.right);
}
return list;
}
}
P32_2: 分行从上到下打印二叉树
从上到下打印二叉树,同一层的节点按从从左到右的顺序打印,每一层打印到一行。
package jianzhi_offer;
import java.util.LinkedList;
import java.util.Queue;
import jianzhi_offer.Print.TreeNode;
public class P32_2_Solution {
/*
* 二叉树按层打印
* 解题思路:还是按照层次遍历的思想,增加两个变量toBePrinted当前层还没有打印的节点; nextLevel表示下一层中的节点数
*/
public void printLevel(TreeNode root) {
if(root == null)
return;
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
int toBePrinted = 1;
int nextLevel = 0;
while(!que.isEmpty()) {
TreeNode temp = que.peek();
System.out.print(temp.val);
que.poll();
toBePrinted--;
if(root.left != null) {
que.offer(root.left);
nextLevel++;
}
if(root.right != null) {
que.offer(root.right);
nextLevel++;
}
if(toBePrinted == 0) {
System.out.println();
toBePrinted = nextLevel;
nextLevel = 0;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}