def insertNode(self, node, x): if node.elem == x: print("X already exists!!") return if x < node.elem: if node.leftChild is None: newNode = Zone(x) node.leftChild = newNode newNode.parent = node else: self.insertNode(node.leftChild, x) else: #if x > node.elem if node.rightChild is None: newNode = Zone(x) node.rightChild = newNode newNode.parent = node else: self.insertNode(node.rightChild, x)
def sizeBalance(self, node): if node == None: print("is none", end=' ') return print("Balancing " + str(node.elem)) if self.isBalanced(node): print(str(node.elem) + " is balanced") self.sizeBalance(node.leftChild) print("left " + '(' + str(node.elem) + ')') self.sizeBalance(node.rightChild) print("right " + '(' + str(node.elem) + ')') else: print(str(node.elem) + " is NOT balanced") if self.size(node.leftChild) > self.size(node.rightChild): print("Thera are more nodes on the left") predecessor = node.leftChild while predecessor.rightChild is not None: predecessor = predecessor.rightChild successor = node.rightChild if successor is not None: #there might be no nodes in the right subtree yet while successor.leftChild is not None: successor = successor.leftChild newNode = Zone(node.elem) newNode.members = node.members if successor is not None: successor.leftChild = newNode newNode.parent = successor else: node.rightChild = newNode newNode.parent = node node.elem = predecessor.elem node.members = predecessor.members self.remove(predecessor.elem) print() if node == self.__root: print("NEW ROOT: " + str(node.elem)) else: print("NEW SUBTREE ROOT: " + str(node.elem)) print() self.sizeBalance(node) else: print("There are more nodes on the right") predecessor = node.leftChild if predecessor is not None: while predecessor.rightChild is not None: predecessor = predecessor.rightChild successor = node.rightChild while successor.leftChild is not None: successor = successor.leftChild newNode = Zone(node.elem) newNode.members = node.members if predecessor is not None: predecessor.rightChild = newNode newNode.parent = predecessor else: node.leftChild = newNode newNode.parent = node node.elem = successor.elem node.members = successor.members self.remove(successor.elem) print() if node == self.__root: print("NEW ROOT: " + str(node.elem)) else: print("NEW SUBTREE ROOT: " + str(node.elem)) print() self.sizeBalance(node)