package Leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
/**
* @Author: YCKJ3803
* @Date: 2021/2/3 13:50
* @Description: 层序打印二叉树。这是非常简单的一题。就是用队列!!!!!
* 先从队列中取出一个,再往队列插入左右节点。
*/
public class LevelPrintTree {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
private static int[] levelPrint(TreeNode root) {
if (root == null) {
//不能返回null,要返回初始化的长度为0的数组。
return new int[0];
}
//初始化列表res为空,包含root的list队列
ArrayList<TreeNode> res = new ArrayList();
//初始化队列
Queue<TreeNode> list = new LinkedList<>();
list.add(root);
//BFS 队列为空时跳出
while (!list.isEmpty()) { // 不能用list!= null
//出队
TreeNode node = list.poll();
//出队的加至列表尾部 (列表不能用int数组表示,太简单了,没有add方法)
res.add(node);
//入队
if (node.left != null) {
list.add(node.left);
}
if (node.right != null) {
list.add(node.right);
}
}
// 再将ArrayList类型的res付给int[]类型的result
int[] result = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
result[i] = res.get(i).val;
}
return result;
}
public static void main(String[] args) {
// 3
// / \
// 9 20
// / \
// 15 7
TreeNode root = new TreeNode();
root.val = 3;
root.left = new TreeNode();
root.left.val = 9;
root.right = new TreeNode();
root.right.val = 20;
root.right.left = new TreeNode();
root.right.left.val = 15;
root.right.right = new TreeNode();
root.right.right.val = 7;
TreeNode root2 = new TreeNode();
System.out.println(Arrays.toString(levelPrint(root)));
System.out.println(Arrays.toString(levelPrint(root2)));
}
}