python用字典的方式实现一个多叉树
时间: 2023-06-06 09:05:04 浏览: 50
可以这样实现:
```python
class TreeNode:
def __init__(self, value):
self.value = value
self.children = {}
def add_node(root, node_value, parent_value=None):
node = TreeNode(node_value)
if parent_value is None:
root = node
else:
parent = find_node(root, parent_value)
parent.children[node_value] = node
return root
def find_node(node, value):
if node.value == value:
return node
for child in node.children.values():
found = find_node(child, value)
if found is not None:
return found
return None
```
这里用了一个 `TreeNode` 类表示节点,每个节点有一个 `value` 属性表示节点的值,一个`children` 字典表示子节点。`add_node` 方法用于往树里添加节点,如果不指定父节点,则新节点为根节点;否则就找到父节点,并将新节点加到父节点的 children 中。`find_node` 方法用于按值找到某个节点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)