使用python语言完成如下操作:我将会输入依次删除一个二叉树各叶节点的删除顺序,请你输出所有叶节点被删除前该二叉树的先序遍历
时间: 2024-01-24 22:17:06 浏览: 227
以下是使用 Python 语言实现的代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def preorder_traversal(root):
if root is None:
return []
return [root.val] + preorder_traversal(root.left) + preorder_traversal(root.right)
def delete_leaves(root, sequence):
if root is None:
return None
if root.left is None and root.right is None:
sequence.append(root.val)
return None
root.left = delete_leaves(root.left, sequence)
root.right = delete_leaves(root.right, sequence)
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)
# 依次删除叶节点并输出先序遍历
for i in range(7):
sequence = []
root = delete_leaves(root, sequence)
print(preorder_traversal(root))
```
使用上述代码,我们可以构造一个二叉树并依次删除所有叶节点,同时输出每次删除前的先序遍历结果。
阅读全文