fork download
  1. class Node:
  2. def __init__(self, key):
  3. self.left = None
  4. self.right = None
  5. self.data = key
  6.  
  7.  
  8. def insert(root, key):
  9.  
  10. if root is None:
  11. root = Node(key)
  12.  
  13. elif root.data > key:
  14. root.left = insert(root.left, key)
  15.  
  16. elif root.data < key:
  17. root.right = insert(root.right, key)
  18.  
  19. return root
  20.  
  21. def inorder(root):
  22. if root != None:
  23. inorder(root.left)
  24. print(root.data, end = " ")
  25. inorder(root.right)
  26.  
  27. def mostlyRight(root):
  28.  
  29. if root.left != None:
  30. root = root.left
  31.  
  32. return root
  33.  
  34. def delete(root, key):
  35.  
  36. if root is None:
  37. return root
  38. elif root.data < key:
  39. root.right = delete(root.right, key)
  40. elif root.data > key:
  41. root.left = delete(root.left, key)
  42. else:
  43. if root.left is None and root.right is None:
  44. root = None
  45. elif root.left == None:
  46. temp = root.right
  47. root = None
  48. return temp
  49.  
  50. elif root.right == None:
  51. temp = root.left
  52. root = None
  53. return temp
  54. elif root.left is not None and root.right is not None:
  55. temp = mostlyRight(root.right)
  56. root.data = temp.data
  57. root.right = delete(root.right, temp.data)
  58.  
  59.  
  60. return root
  61.  
  62.  
  63. def search(root, key):
  64.  
  65. pass
  66.  
  67.  
  68. def main():
  69. root = Node(10)
  70. insert(root, 4)
  71. insert(root, 7)
  72. insert(root, 3)
  73. insert(root, -3)
  74. insert(root, 13)
  75. insert(root, 5)
  76. inorder(root)
  77.  
  78. print()
  79.  
  80. key = 13
  81. print("Delete %d" % key)
  82. delete(root, key)
  83.  
  84. inorder(root)
  85. main()
  86.  
Success #stdin #stdout 0.02s 9256KB
stdin
Standard input is empty
stdout
-3 3 4 5 7 10 13 
Delete 13
-3 3 4 5 7 10