java树形菜单代码实现
时间: 2023-11-20 12:51:25 浏览: 76
好的,以下是一个简单的 Java 树形菜单代码实现:
```
import java.util.ArrayList;
import java.util.List;
public class TreeNode {
private int id;
private String name;
private List<TreeNode> children;
public TreeNode(int id, String name) {
this.id = id;
this.name = name;
this.children = new ArrayList<>();
}
public void addChild(TreeNode child) {
children.add(child);
}
public void printTree() {
printTree(0);
}
private void printTree(int level) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < level; i++) {
sb.append(" ");
}
sb.append(name);
System.out.println(sb.toString());
for (TreeNode child : children) {
child.printTree(level + 1);
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1, "Root");
TreeNode node1 = new TreeNode(2, "Node 1");
TreeNode node2 = new TreeNode(3, "Node 2");
TreeNode node3 = new TreeNode(4, "Node 3");
TreeNode node4 = new TreeNode(5, "Node 4");
root.addChild(node1);
root.addChild(node2);
node1.addChild(node3);
node2.addChild(node4);
root.printTree();
}
}
```
这个实现中,我们定义了一个 `TreeNode` 类,每个节点包含一个 ID 和一个名称,以及一个子节点列表。我们可以通过 `addChild` 方法向节点添加子节点,通过 `printTree` 方法打印整个树形结构。
阅读全文