说明:
给出一个数组,将数组转化成二叉树;
给出一颗二叉树,从上到下依次打印二叉树内容;
import java.util.ArrayList;
import java.util.LinkedList;
public class MyBinaryTree {
static class TreeNode {
Object data;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(Object data, TreeNode left, TreeNode right) {
this.data = data;
this.left = left;
this.right = right;
}
}
public static void main(String[] args) {
//Object[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
Object[] arr = {1,2,3,4,5,6,7,8,9};
TreeNode treeNode = MyBinaryTree.arrayToTreeNode(arr);
ArrayList<ArrayList<TreeNode>> result = MyBinaryTree.printTreeNode(treeNode);
System.out.println("开始打印二叉树");
StringBuilder builder = new StringBuilder("[ ");
for (ArrayList<TreeNode> objects : result) {
for (TreeNode object : objects) {
builder.append(object.data.toString()).append(", ");
}
}
builder.deleteCharAt(builder.length()-2);
builder.append("]");
System.out.println(builder.toString());
System.out.println("打印二叉树完成");
}
private static ArrayList<ArrayList<TreeNode>> printTreeNode(TreeNode treeNode) {
LinkedList<TreeNode> queue = new LinkedList<>();
ArrayList<ArrayList<TreeNode>> result = new ArrayList<>();
queue.add(treeNode);
if (!queue.isEmpty()) {
ArrayList<TreeNode> list = new ArrayList<>();
int size = queue.size();
while (size-- > 0) {
TreeNode poll = queue.poll();
if (poll == null) continue;
list.add(poll);
queue.add(poll.left);
queue.add(poll.right);
size =queue.size();
}
result.add(list);
}
return result;
}
private static TreeNode arrayToTreeNode(Object[] arr) {
if (arr == null || arr.length == 0) {
return new TreeNode();
}
ArrayList<TreeNode> nodes = new ArrayList<>(arr.length);
// 二叉树最后一个父节点index 为arr.length/2-1
// 除了父节点其他的都是子节点
for (int i = 0; i < arr.length; i++) {
TreeNode treeNode = new TreeNode();
treeNode.data = arr[i];
nodes.add(treeNode);
}
// 添加子节点
for (int i = 0; i < nodes.size()/2 - 1; i++) {
TreeNode treeNode = nodes.get(i);
treeNode.left = nodes.get(i * 2 + 1);
treeNode.right = nodes.get(i * 2 + 2);
}
//节点数为偶数时最后一个父节点没有右子节点
TreeNode lastParentNode = nodes.get(arr.length/2-1);
lastParentNode.left = nodes.get((arr.length/2-1) * 2 + 1);
if (arr.length%2 != 0){
lastParentNode.right = nodes.get((arr.length/2-1) * 2 + 2);
}
return nodes.get(0);
}
}