写出孩子表示法代码并实现
时间: 2024-02-12 22:04:13 浏览: 29
孩子表示法是一种树的存储方式,它将每个节点的孩子节点保存在一个单链表中。以下是用 Python 实现孩子表示法的代码:
```python
class TreeNode:
def __init__(self, data):
self.data = data
self.firstChild = None # 第一个孩子节点
self.nextSibling = None # 下一个兄弟节点
class ChildTree:
def __init__(self, data=None, firstChild=None, nextSibling=None):
self.root = TreeNode(data)
self.root.firstChild = firstChild
self.root.nextSibling = nextSibling
def add_child(self, data):
if self.root.firstChild is None:
self.root.firstChild = TreeNode(data)
else:
p = self.root.firstChild
while p.nextSibling is not None:
p = p.nextSibling
p.nextSibling = TreeNode(data)
def print_tree(self):
def dfs(node):
if node is None:
return
print(node.data, end=' ')
dfs(node.firstChild)
dfs(node.nextSibling)
dfs(self.root)
```
以上代码中,`TreeNode` 类表示树的节点,其中 `firstChild` 属性表示当前节点的第一个孩子节点,`nextSibling` 属性表示当前节点的下一个兄弟节点。`ChildTree` 类表示孩子表示法的树,其中 `root` 属性表示根节点,`add_child` 方法用于添加孩子节点,`print_tree` 方法用于打印树的结构。
以下是一个使用示例:
```python
t = ChildTree(1)
t.add_child(2)
t.add_child(3)
t.root.firstChild.nextSibling = ChildTree(4)
t.root.firstChild.nextSibling.add_child(5)
t.print_tree() # 输出:1 2 3 4 5
```
以上代码中,我们创建了一个根节点为 1 的孩子表示法的树,然后添加了两个孩子节点 2 和 3,又添加了一个孩子节点 4,这个孩子节点 4 又有一个孩子节点 5。最后我们打印了整个树的结构,输出为 `1 2 3 4 5`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)