python删除二叉树节点
时间: 2024-03-06 19:19:53 浏览: 142
以下是 Python 中删除二叉树节点的代码示例:
```python
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def inorder(temp):
if (not temp):
return
inorder(temp.left)
print(temp.val, end=" ")
inorder(temp.right)
def deleteDeepest(root, d_node):
q = []
q.append(root)
while (len(q)):
temp = q.pop(0)
if temp is d_node:
temp = None
return
if temp.right:
if temp.right is d_node:
temp.right = None
return
else:
q.append(temp.right)
if temp.left:
if temp.left is d_node:
temp.left = None
return
else:
q.append(temp.left)
def deletion(root, key):
if root == None:
return None
if root.left == None and root.right == None:
if root.key == key:
return None
else:
return root
key_node = None
q = []
q.append(root)
while (len(q)):
temp = q.pop(0)
if temp.val == key:
key_node = temp
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
if key_node:
x = temp.val
deleteDeepest(root, temp)
key_node.val = x
return root
root = Node(10)
root.left = Node(11)
root.left.left = Node(7)
root.left.right = Node(12)
root.right = Node(9)
root.right.left = Node(15)
root.right.right = Node(8)
print("The tree before the deletion:")
inorder(root)
key = 11
root = deletion(root, key)
print()
print("The tree after the deletion;")
inorder(root)
```
这段代码中,我们首先定义了一个 `Node` 类,表示二叉树中的节点。然后,我们定义了三个函数:`inorder` 函数用于中序遍历二叉树,`deleteDeepest` 函数用于删除二叉树中最深的节点,`deletion` 函数用于删除指定的节点。
在 `deletion` 函数中,我们首先遍历整个二叉树,找到要删除的节点。然后,我们将这个节点的值替换为其右子树中最深的节点的值,然后删除这个最深的节点。最后,我们返回修改后的二叉树根节点。
注意,这段代码假设每个节点的值都是唯一的。如果有多个节点具有相同的值,这段代码可能无法正确删除指定的节点。
阅读全文