非完全二叉树与完全二叉树的代码区别
时间: 2024-03-25 21:34:53 浏览: 168
非完全二叉树与完全二叉树的代码区别主要体现在对节点的插入和删除操作上。
对于非完全二叉树,节点的插入操作可以在任意位置进行,而节点的删除操作也可以删除任意节点。这是因为非完全二叉树没有严格的规定节点的插入和删除位置,可以根据需要进行调整。
而对于完全二叉树,节点的插入操作只能在最后一层的最右边进行,即按照从左到右的顺序依次插入。节点的删除操作也只能删除最后一层最右边的节点。这是因为完全二叉树要求保持树的平衡性,所以只能在最后一层进行插入和删除操作。
下面是非完全二叉树和完全二叉树的代码示例:
非完全二叉树的插入操作:
```python
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(root, data):
if root is None:
root = Node(data)
else:
if root.left is None:
root.left = insert(root.left, data)
else:
root.right = insert(root.right, data)
return root
```
非完全二叉树的删除操作:
```python
def delete(root, data):
if root is None:
return root
if data < root.data:
root.left = delete(root.left, data)
elif data > root.data:
root.right = delete(root.right, data)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = minValueNode(root.right)
root.data = temp.data
root.right = delete(root.right, temp.data)
return root
def minValueNode(node):
current = node
while(current.left is not None):
current = current.left
return current
```
完全二叉树的插入操作:
```python
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(root, data):
if root is None:
root = Node(data)
else:
queue = []
queue.append(root)
while len(queue) > 0:
node = queue.pop(0)
if node.left is None:
node.left = Node(data)
break
else:
queue.append(node.left)
if node.right is None:
node.right = Node(data)
break
else:
queue.append(node.right)
return root
```
完全二叉树的删除操作:
```python
def delete(root, data):
if root is None:
return root
if root.left is None and root.right is None:
if root.data == data:
return None
else:
return root
queue = []
queue.append(root)
while len(queue) > 0:
node = queue.pop(0)
if node.data == data:
temp = getDeepestNode(root)
node.data = temp.data
deleteDeepestNode(root, temp)
break
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
return root
def getDeepestNode(root):
queue = []
queue.append(root)
while len(queue) > 0:
node = queue.pop(0)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
return node
def deleteDeepestNode(root, node):
queue = []
queue.append(root)
while len(queue) > 0:
temp = queue.pop(0)
if temp is node:
temp = None
return
if temp.right is not None:
if temp.right is node:
temp.right = None
return
else:
queue.append(temp.right)
if temp.left is not None:
if temp.left is node:
temp.left = None
return
else:
queue.append(temp.left)
```
阅读全文