树的孩子表示法代码
时间: 2023-11-22 17:53:18 浏览: 45
下面是一份示例代码,实现了树的孩子表示法:
```python
class TreeNode:
def __init__(self, value):
self.value = value
self.children = []
def add_child(self, child_node):
self.children.append(child_node)
def remove_child(self, child_node):
if child_node in self.children:
self.children.remove(child_node)
class Tree:
def __init__(self, root_node):
self.root = root_node
def get_root(self):
return self.root
```
在这个代码中,`TreeNode` 类表示树的节点,它包含一个值和一个子节点列表。`Tree` 类则表示整棵树,它包含一个根节点。可以通过 `add_child` 和 `remove_child` 方法来添加或移除节点的子节点。
使用这个代码,我们可以创建一棵树:
```python
# 创建节点
root_node = TreeNode('A')
child1 = TreeNode('B')
child2 = TreeNode('C')
child3 = TreeNode('D')
# 添加子节点
root_node.add_child(child1)
root_node.add_child(child2)
child2.add_child(child3)
# 创建树
tree = Tree(root_node)
```
这棵树的结构如下:
```
A
/ \
B C
/
D
```