1、一棵树采用孩子链存储结构/或长子兄弟链存储结构(任选一种),尝试编程实现: (1)创建一棵树 (2)设计一个算法求高度 (3)设计一个算法实现树的层次遍历 设计两个算法实现先根遍历和后根遍历python
时间: 2023-06-10 18:03:52 浏览: 67
好的,您的第一个问题是关于树的孩子链存储结构或长子兄弟链存储结构的编程实现,包括创建一棵树、求高度、实现树的层次遍历、先根遍历和后根遍历。
下面是代码实现:
```python
# 树的节点类
class TreeNode:
def __init__(self, val, child=None, sibling=None):
self.val = val
self.child = child # 孩子
self.sibling = sibling # 兄弟
# 创建一棵树
def createTree():
root = TreeNode('A', child=TreeNode('B', child=TreeNode('E')), sibling=TreeNode('C', child=TreeNode('F'), sibling=TreeNode('D')))
return root
# 求树的高度
def getHeight(root):
if root is None:
return 0
height = 1
temp = root.child
while temp is not None:
height = max(height, getHeight(temp) + 1)
temp = temp.sibling
return height
# 树的层次遍历
def levelOrderTraversal(root):
if root is None:
return []
queue = [root]
res = []
while queue:
level = []
for _ in range(len(queue)):
node = queue.pop(0)
level.append(node.val)
if node.child:
queue.append(node.child)
sibling = node.sibling
while sibling:
queue.append(sibling)
sibling = sibling.sibling
res.append(level)
return res
# 先根遍历
def preOrder(root):
if root is None:
return []
res = [root.val]
temp = root.child
while temp is not None:
res += preOrder(temp)
temp = temp.sibling
return res
# 后根遍历
def postOrder(root):
if root is None:
return []
res = []
temp = root.child
while temp is not None:
res += postOrder(temp)
temp = temp.sibling
res.append(root.val)
return res[::-1]
```
感谢您使用ChitGPT进行咨询,如果还有其他问题,请随时提出。
阅读全文