java 输出树形结构工具类
时间: 2023-12-23 08:47:03 浏览: 137
JAVA排序树形结构数据构建,这个工具类就够了
以下是一个 Java 工具类,可以将树形结构数据输出为字符串:
```java
import java.util.List;
public class TreePrinter {
private static final String LINE_PREFIX = " ";
private static final String BRANCH_PREFIX = "│ ";
private static final String LAST_BRANCH_PREFIX = "└── ";
public static <T extends TreeNode> String printTree(T root) {
StringBuilder sb = new StringBuilder();
printNode(sb, "", root, true);
return sb.toString();
}
private static <T extends TreeNode> void printNode(StringBuilder sb, String prefix, T node, boolean isLast) {
sb.append(prefix);
if (isLast) {
sb.append(LAST_BRANCH_PREFIX);
prefix += LINE_PREFIX;
} else {
sb.append(BRANCH_PREFIX);
prefix += BRANCH_PREFIX;
}
sb.append(node.getName());
sb.append("\n");
List<T> children = node.getChildren();
if (children != null) {
int size = children.size();
for (int i = 0; i < size; i++) {
boolean last = i == size - 1;
printNode(sb, prefix, children.get(i), last);
}
}
}
public interface TreeNode {
String getName();
List<? extends TreeNode> getChildren();
}
}
```
使用方法:
1. 实现 `TreeNode` 接口,并实现其中的两个方法 `getName()` 和 `getChildren()`,分别返回节点名称和子节点列表。
2. 调用 `TreePrinter.printTree(root)` 方法,其中 `root` 为树的根节点。
以下是一个简单的例子:
```java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
TreeNode root = new Node("root");
Node node1 = new Node("node1");
Node node2 = new Node("node2");
Node node3 = new Node("node3");
Node node4 = new Node("node4");
Node node5 = new Node("node5");
Node node6 = new Node("node6");
root.addChild(node1);
root.addChild(node2);
root.addChild(node3);
node2.addChild(node4);
node2.addChild(node5);
node3.addChild(node6);
String tree = TreePrinter.printTree(root);
System.out.println(tree);
}
static class Node implements TreePrinter.TreeNode {
private String name;
private List<Node> children;
public Node(String name) {
this.name = name;
this.children = new ArrayList<>();
}
public void addChild(Node child) {
children.add(child);
}
@Override
public String getName() {
return name;
}
@Override
public List<Node> getChildren() {
return children;
}
}
}
```
输出结果为:
```
└── root
├── node1
├── node2
│ ├── node4
│ └── node5
└── node3
└── node6
```
阅读全文