二叉树 树形打印 java
时间: 2023-11-18 09:59:50 浏览: 105
下面是二叉树树形打印的Java代码实现:
```
public class BinaryTreePrinter {
public static void printNode(TreeNode root) {
int maxLevel = maxLevel(root);
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
private static void printNodeInternal(List<TreeNode> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int edgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
printWhitespaces(firstSpaces);
List<TreeNode> newNodes = new ArrayList<>();
for (TreeNode node : nodes) {
if (node != null) {
System.out.print(node.val);
newNodes.add(node.left);
newNodes.add(node.right);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= edgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
printWhitespaces(edgeLines + edgeLines + i + 1);
continue;
}
if (nodes.get(j).left != null)
System.out.print("/");
else
printWhitespaces(1);
printWhitespaces(i + i - 1);
if (nodes.get(j).right != null)
System.out.print("\\");
else
printWhitespaces(1);
printWhitespaces(edgeLines + edgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
}
private static void printWhitespaces(int count) {
for (int i = 0; i < count; i++)
System.out.print(" ");
}
private static int maxLevel(TreeNode node) {
if (node == null)
return 0;
return Math.max(maxLevel(node.left), maxLevel(node.right)) + 1;
}
private static boolean isAllElementsNull(List list) {
for (Object object : list) {
if (object != null)
return false;
}
return true;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
printNode(root);
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
```
通过调用`printNode`方法,可以打印出二叉树的树形结构。其中`TreeNode`类表示二叉树节点,`val`表示节点的值,`left`和`right`分别表示节点的左右子节点。
阅读全文