Advertisement
Guest User

therest

a guest
Apr 19th, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. def is_correct_rb_tree(tree):
  2. if tree.root is None:
  3. return True
  4.  
  5. if tree.root.color is not Colors.black:
  6. return False
  7.  
  8. if black_height(tree.root) == 0:
  9. return False
  10.  
  11. return check_children(tree.root)
  12.  
  13. def check_children(node):
  14. if node is None:
  15. return True
  16.  
  17. if node.color is Colors.red:
  18. color_left = Colors.black
  19. if node.left is not None:
  20. color_left = node.left.color
  21. color_right = Colors.black
  22. if node.right is not None:
  23. color_right = node.right.color
  24. return color_left is Colors.black and color_right is Colors.black and check_children(node.left) and check_children(node.right)
  25. else:
  26. return check_children(node.left) and check_children(node.right)
  27.  
  28. def black_height(node):
  29. if node is None:
  30. return 1
  31.  
  32. left_height = black_height(node.left)
  33. if left_height is 0:
  34. return 0
  35.  
  36. right_height = black_height(node.right)
  37. if right_height is 0:
  38. return 0
  39.  
  40. if left_height != right_height:
  41. return 0
  42. else:
  43. val = left_height
  44. if node.color is Colors.black:
  45. val += 1
  46. return val
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement