C
C
cyberkilla2020-06-15 11:36:21
Python
cyberkilla, 2020-06-15 11:36:21

How to rewrite the avl-balancing algorithm to work with large arrays?

The program breaks when entering large arrays. Could it be that repeated numbers will inevitably occur on large volumes, and it is worth rewriting this part? Or is the error something else?

import random

class node(object): #узлы дерева

  def __init__(self, val):
    self.val = val 
    self.left = 0
    self.right = 0
    self.height = 1

class AVL_Tree(object): 

  def get_height(self, p):

    if not p:
      return 0
  
    return p.height


  def bfactor(self, p):

    if not p:
      return 0
  
    return self.get_height(p.left) - self.get_height(p.right) 

  
  def fixheight(self, p):
    p.height = 1 + max(self.get_height(p.left), self.get_height(p.right))

  def how_high(self, p):
    return 1 + max(self.get_height(p.left), self.get_height(p.right))


  def rotateright(self, p): # правый поворот вокруг p

    q = p.left 
    buf = q.right 
  
    q.right = p 
    p.left = buf 
  
    self.fixheight(p)
    self.fixheight(q)

    return q 


  def rotateleft(self, q): # левый поворот вокруг q
    
    p = q.right 
    buf = p.left 
   
    p.left = q 
    q.right = buf 
  
    self.fixheight(q)
    self.fixheight(p)

    return p 


  def insert(self, p, k):

    if not p:
      return node(k) 
    elif k < p.val:
      p.left = self.insert(p.left, k) 
    else: 
      p.right = self.insert(p.right, k) 
  
    self.fixheight(p)
    balance = self.bfactor(p) 

    if balance > 1 and k < p.left.val:
      return self.rotateright(p) 
  
    if balance < -1 and k > p.right.val:
      return self.rotateleft(p) 
  
    if balance > 1 and k > p.left.val:
      p.left = self.rotateleft(p.left) 
      return self.rotateright(p) 

    if balance < -1 and k < p.right.val:
      p.right = self.rotateright(p.right) 
      return self.rotateleft(p) 
  
    return p 

  def pre_order(self, p):
    
    if not p:
      return
  
    print("{0} ".format(p.val), end="") 
    self.pre_order(p.left) 
    self.pre_order(p.right) 

newTree = AVL_Tree() 
root = None
source=[]

for i in range(10):
  p=random.randint(1, 100)
  source.append(p)
  root = newTree.insert(root, p)
  
print('Исходное дерево:', *source)
print('AVL-дерево', end = ': ') 
newTree.pre_order(root) 
print("\nВысота дерева:", newTree.how_high(root))

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question