fork download
  1. class Node:
  2.  
  3. def __init__(self, key):
  4.  
  5. self.left = None
  6.  
  7. self.right = None
  8.  
  9. self.data = key
  10.  
  11. def search(root, key):
  12.  
  13. if root is None:
  14.  
  15. return False
  16.  
  17. elif root.data == key:
  18.  
  19. return True
  20.  
  21. elif root.data > key:
  22.  
  23. return search(root.left, key)
  24.  
  25. else:
  26. return search(root.right, key)
  27.  
  28. def insert(root, val):
  29.  
  30. if root is None:
  31.  
  32. print("added to BST: ", val)
  33.  
  34. return Node(val)
  35.  
  36. elif root.data > val:
  37.  
  38. root.left = insert(root.left, val)
  39.  
  40. elif root.data < val:
  41.  
  42. root.right = insert(root.right, val)
  43.  
  44. return root
  45.  
  46. def inorder(root):
  47.  
  48. if root.left is not None:
  49.  
  50. inorder(root.left)
  51.  
  52. print(root.data, end = " ")
  53.  
  54. if root.right is not None:
  55.  
  56. inorder(root.right)
  57.  
  58. def preorder(root):
  59.  
  60. print(root.data, end = " ")
  61.  
  62. if root.left is not None:
  63.  
  64. preorder(root.left)
  65.  
  66. if root.right is not None:
  67.  
  68. preorder(root.right)
  69.  
  70. def main():
  71.  
  72. vec = [ 55, 22, 11, 22, 0, 33, 44, 555, 101, -101 ]
  73.  
  74. print( vec )
  75.  
  76. root = Node(-1 )
  77.  
  78. for i in vec:
  79.  
  80. insert( root, i )
  81.  
  82.  
  83. print("Inorder traversal:", end = " ")
  84.  
  85. inorder(root)
  86.  
  87. print()
  88.  
  89. print("Preorder traversal:", end = " ")
  90.  
  91. preorder(root)
  92.  
  93. key = -101
  94. r = search(root, key)
  95.  
  96. print()
  97.  
  98. if r is True:
  99.  
  100. print("%d is Found" % key)
  101.  
  102. else:
  103.  
  104. print("%d Not Found" % key)
  105. main()
  106.  
Success #stdin #stdout 0.02s 9172KB
stdin
Standard input is empty
stdout
[55, 22, 11, 22, 0, 33, 44, 555, 101, -101]
added to BST:  55
added to BST:  22
added to BST:  11
added to BST:  0
added to BST:  33
added to BST:  44
added to BST:  555
added to BST:  101
added to BST:  -101
Inorder traversal: -101 -1 0 11 22 33 44 55 101 555 
Preorder traversal: -1 -101 55 22 11 0 33 44 555 101 
-101 is Found