m2skills

isBalanced python

Jun 22nd, 2018
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # program to check if a given binary tree is balanced or not
  3.  
  4. # node class
  5. class node:
  6.     def __init__(self, element):
  7.         self.data = element
  8.         self.hd = -1
  9.         self.left = None
  10.         self.right = None
  11.  
  12. # function to find the height of a binary tree
  13. def height(root):
  14.     if root is None:
  15.         return 0
  16.  
  17.     return 1 + max(height(root.left), height(root.right))
  18.  
  19.  
  20. # function to check if the tree is a height balanced tree or not
  21. def isBalanced(root):
  22.     if root is None:
  23.         return True
  24.  
  25.     # get the heights of the left and the right subtrees
  26.     left_height = height(root.left)
  27.     right_height = height(root.right)
  28.     # if the difference between heights of the left and right subtrees is less than 2
  29.     # and left and right subtrees are also balanced then return True
  30.     return abs(left_height - right_height) <= 1 and isBalanced(root.left) and isBalanced(root.right)
  31.  
  32.  
  33.  
  34. head = node(1)
  35. head.left = node(2)
  36. head.right = node(3)
  37. head.left.left = node(4)
  38. head.left.right = node(5)
  39. head.right.right = node(6)
  40. head.left.left.right = node(7)
  41. head.right.right.left = node(8)
  42. head.left.left.right.left = node(9)
  43. head.left.left.right.left.left = node(10)
  44. head.right.right.left.right = node(11)
  45.  
  46.  
  47. head2 = node(5)
  48. head2.left = node(2)
  49. head2.right = node(12)
  50. head2.left.left = node(-4)
  51. head2.left.right = node(3)
  52. head2.right.left = node(9)
  53. head2.right.right = node(21)
  54. head2.right.right.left = node(19)
  55. head2.right.right.right = node(25)
  56.  
  57. print("Tree #1 is Balanced : " + str(isBalanced(head)))
  58. print("Tree #2 is Balanced : " + str(isBalanced(head2)))
Add Comment
Please, Sign In to add comment