用java写一个楼栋单元房屋的树形结构
时间: 2023-05-15 22:07:33 浏览: 154
非常感谢您的提问。以下是一个用 Java 编写的楼栋单元房屋的树形结构示例代码:
```
class TreeNode {
private String name;
private List<TreeNode> children;
public TreeNode(String name) {
this.name = name;
this.children = new ArrayList<>();
}
public void addChild(TreeNode child) {
this.children.add(child);
}
public String getName() {
return this.name;
}
public List<TreeNode> getChildren() {
return this.children;
}
}
public class Building {
public static void main(String[] args) {
TreeNode building = new TreeNode("Building");
TreeNode unit1 = new TreeNode("Unit 1");
TreeNode unit2 = new TreeNode("Unit 2");
TreeNode unit3 = new TreeNode("Unit 3");
TreeNode floor1 = new TreeNode("Floor 1");
TreeNode floor2 = new TreeNode("Floor 2");
TreeNode floor3 = new TreeNode("Floor 3");
TreeNode room1 = new TreeNode("Room 1");
TreeNode room2 = new TreeNode("Room 2");
TreeNode room3 = new TreeNode("Room 3");
room1.addChild(new TreeNode("Bed"));
room1.addChild(new TreeNode("Desk"));
room1.addChild(new TreeNode("Chair"));
room2.addChild(new TreeNode("Bed"));
room2.addChild(new TreeNode("Desk"));
room2.addChild(new TreeNode("Chair"));
room3.addChild(new TreeNode("Bed"));
room3.addChild(new TreeNode("Desk"));
room3.addChild(new TreeNode("Chair"));
floor1.addChild(room1);
floor1.addChild(room2);
floor2.addChild(room3);
unit1.addChild(floor1);
unit2.addChild(floor2);
unit3.addChild(new TreeNode("Empty"));
building.addChild(unit1);
building.addChild(unit2);
building.addChild(unit3);
printTree(building, 0);
}
private static void printTree(TreeNode node, int depth) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; i++) {
sb.append("-");
}
sb.append(node.getName());
System.out.println(sb.toString());
for (TreeNode child : node.getChildren()) {
printTree(child, depth + 1);
}
}
}
```
这段代码使用了树形结构来表示楼栋、单元、楼层和房间之间的关系。每个节点都有一个名称和一个子节点列表,可以通过 addChild 方法来添加子节点。在示例中,我们创建了一个 Building 节点作为根节点,然后添加了三个 Unit 节点作为 Building 的子节点,每个 Unit 节点又包含了若干个 Floor 节点,每个 Floor 节点又包含了若干个 Room 节点,最后每个 Room 节点又包含了三个具体的物品节点。最后,我们使用递归的方式遍历整个树形结构,并打印出每个节点的名称和深度,以展示树形结构的形态。