若一棵树采用孩子链存储结构t存储,python设计一个算法求其高度。包括主函数
时间: 2023-06-14 17:07:24 浏览: 70
以下是基于孩子链存储结构的树求高度的 Python 代码,包括主函数:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.child = []
def getHeight(root):
if not root:
return 0
height = 0
for child in root.child:
height = max(height, getHeight(child))
return height + 1
# 测试
if __name__ == '__main__':
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
node7 = TreeNode(7)
node8 = TreeNode(8)
node9 = TreeNode(9)
node10 = TreeNode(10)
node11 = TreeNode(11)
node1.child = [node2, node3, node4]
node2.child = [node5, node6]
node3.child = [node7, node8, node9]
node4.child = [node10]
node6.child = [node11]
print(getHeight(node1)) # 输出 4
```
其中,`TreeNode` 是树节点的类,包括节点的值和子节点列表。`getHeight` 是递归求树高的函数,如果根节点为空,返回 0,否则对于每个子节点,递归计算其高度,并取最大值,最后加上 1,即为树的高度。在主函数中,我们构建了一棵树并测试了求高度的函数。
阅读全文