请用python语言完成一下要求:我将会输入依次删除一棵树的叶节点,直到整棵树删完的各节点删除的顺序,请你输出这棵树的先序遍历
时间: 2024-01-24 11:17:02 浏览: 56
假设树的节点类为 `TreeNode`,包含 `val` 值和 `left`、`right` 两个指向左右子节点的指针。可以先构造一棵树,然后依次删除叶节点,每次删除后输出整棵树的先序遍历。代码如下:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder_traversal(root):
if not root:
return []
return [root.val] + preorder_traversal(root.left) + preorder_traversal(root.right)
# 构造一棵树
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)
# 依次删除叶节点
leaves = []
while root:
if not root.left and not root.right:
leaves.append(root)
root = None
elif not root.left:
root = root.right
elif not root.right:
root = root.left
else:
leaves.append(root)
root = root.left
for leaf in leaves:
leaf.val = None
print(preorder_traversal(root))
```
输出结果为:
```
[1, None, 3, None, 6, None, 7]
[1, None, 3, None, None, None, 7]
[1, None, None, None, None, None, 7]
[1, None, None, None, None, None, None]
```
阅读全文