我用python创建了一个二叉树。 deleteNode
功能无效。我想创建一个删除节点和删除树后正常工作的功能。
现在,当我尝试删除树中的节点时,删除了错误的节点。你能帮我怎么编辑代码吗?
import math
class MyCompleteTree:
def __init__ (self):
self.arr = []
self.arr.append(None)
self.count = 0
def isEmpty(self):
if (self.count == 0):
return True
else:
return False
def addNode(self, item):
self.arr.append(item)
self.count = self.count + 1
def getHeight(self):
return int(math.log2(self.count)) +1
def preorder(self, index):
if(index <= self.count):
print(self.arr[index], end=' ')
self.preorder(index * 2)
self.preorder(index * 2 + 1)
def inorder(self, index):
if(index <= self.count):
self.inorder(index * 2)
print(self.arr[index], end=' ')
self.inorder(index * 2 + 1)
def inorderFromRoot(self):
self.inorder(1)
def postorder(self, index):
if(index <= self.count):
self.postorder(index * 2)
self.postorder(index * 2 + 1)
print(self.arr[index], end=' ')
def printLeafNode(self, index):
visit = False
if (index * 2 <= self.count):
visit = True
self.printLeafNode(index * 2)
if (index * 2 + 1 <= self.count):
visit = True
self.printLeafNode(index * 2 + 1)
if visit == False:
print(self.arr[index], end=' ')
def deleteNode(self, item):
if self.count > 1:
if item in self.arr:
self.item = None
self.count = self.count - 1
print(item, "Deleted")
else:
print("No nodes were found in the tree")
else:
print("Tree is empty")