2020 school recruitment written test Xinhua Sanhanmo

2023-01-19   ES

Note: This blog is no longer updated, all the latest articles will be published on personal independent bloglimengting.site. Share technology and record life, welcome everyone to follow

Question description
Print the binary tree from top to bottom, and the same layer nodes output from left to right. Each layer outputs one line.

``````import java.util.ArrayList;
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 {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>();
if (pRoot == null) return arrayLists;
ArrayList<Integer> arrayList = new ArrayList<>();
int count = 0;
int nextLayerCount = 1;
while (!queue.isEmpty()) {
TreeNode treeNode = queue.poll();
count++;
if (treeNode.left != null) {
}
if (treeNode.right != null) {
}
if (count == nextLayerCount) {
count = 0;
nextLayerCount = queue.size();
arrayList = new ArrayList<>();
}
}
return arrayLists;
}
}
``````

source