fork download
  1. # your code goes here
  2. class TreeNode():
  3. def __init__(self, val):
  4. self.val = val
  5. self.left = None
  6. self.right = None
  7.  
  8. class Solution():
  9.  
  10. def insert(self, root, val):
  11.  
  12. if root is None:
  13. root = TreeNode(val)
  14. return root
  15. else:
  16. if val <= root.val:
  17. root.left = self.insert(root.left, val)
  18. else:
  19. root.right = self.insert(root.right, val)
  20. return root
  21. def display(self, root):
  22. if root is None:
  23. return
  24. self.display(root.left)
  25. print(root.val)
  26. self.display(root.right)
  27.  
  28.  
  29. root = None
  30. s = Solution()
  31. root = s.insert(root, 5)
  32. root = s.insert(root, 3)
  33. root = s.insert(root, 2)
  34. root = s.insert(root, 8)
  35. s.display(root)
  36.  
Success #stdin #stdout 0.01s 7144KB
stdin
Standard input is empty
stdout
2
3
5
8