maxim_shlyahtin

Insert

Nov 1st, 2023
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. def getHeight(root):
  2.     if not root:
  3.         return 0
  4.     return root.height
  5.  
  6.  
  7. def getBalance(root):
  8.     if not root:
  9.         return 0
  10.     return getHeight(root.left) - getHeight(root.right)
  11.  
  12.  
  13. def leftRotate(root):
  14.     right_son = root.right
  15.     T2 = right_son.left
  16.  
  17.     right_son.left = root
  18.     root.right = T2
  19.  
  20.     root.height = 1 + max(getHeight(root.left),
  21.                        getHeight(root.right))
  22.     right_son.height = 1 + max(getHeight(right_son.left),
  23.                        getHeight(right_son.right))
  24.  
  25.     return right_son
  26.  
  27.  
  28. def rightRotate(root):
  29.     left_son = root.left
  30.     T3 = left_son.right
  31.  
  32.     left_son.right = root
  33.     root.left = T3
  34.  
  35.     root.height = 1 + max(getHeight(root.left),
  36.                        getHeight(root.right))
  37.     root.height = 1 + max(getHeight(left_son.left),
  38.                        getHeight(left_son.right))
  39.  
  40.     return left_son
  41.  
  42.  
  43. def insert(val, root):
  44.     if not root:
  45.         return Node(val)
  46.     elif val < root.val:
  47.         root.left = insert(val, root.left)
  48.     else:
  49.         root.right = insert(val, root.right)
  50.  
  51.     root.height = 1 + max(getHeight(root.left),
  52.                           getHeight(root.right))
  53.  
  54.     balance = getBalance(root)
  55.  
  56.     if balance > 1 and val < root.left.val:
  57.         return rightRotate(root)
  58.  
  59.     if balance < -1 and val > root.right.val:
  60.         return leftRotate(root)
  61.  
  62.     if balance > 1 and val > root.left.val:
  63.         root.left = leftRotate(root.left)
  64.         return rightRotate(root)
  65.  
  66.     if balance < -1 and val < root.right.val:
  67.         root.right = rightRotate(root.right)
  68.         return leftRotate(root)
  69.  
  70.     return root
Add Comment
Please, Sign In to add comment