二叉树采用二叉链存储,要求交换二叉树的左右子树python代码及主程序
时间: 2023-10-31 09:05:32 浏览: 77
好的,我理解了你的要求。以下是交换二叉树左右子树的python代码及主程序:
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 交换二叉树左右子树的函数
def invertTree(root: TreeNode) -> TreeNode:
if not root:
return None
left = invertTree(root.left) # 递归获取左子树
right = invertTree(root.right) # 递归获取右子树
root.left, root.right = right, left # 交换左右子树
return root
# 主程序
if __name__ == '__main__':
# 构造二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
# 输出交换前的二叉树
print('交换前的二叉树:')
print(root.left.left.val, root.left.val, root.left.right.val)
print(root.val)
print(root.right.left.val, root.right.val, root.right.right.val)
# 交换左右子树
invertTree(root)
# 输出交换后的二叉树
print('交换后的二叉树:')
print(root.right.right.val, root.right.val, root.right.left.val)
print(root.val)
print(root.left.right.val, root.left.val, root.left.left.val)
```
注意,此处的代码仅供学习参考,实际应用中需要根据具体情况做出调整。
阅读全文