rishiilluri

Untitled

Sep 23rd, 2022
758
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. class Node:
  2.     def __init__(self, value):
  3.         self.value = value
  4.         self.left = None
  5.         self.right = None
  6.     def insert(self , value):
  7.         current = self
  8.         previous = None
  9.         while current:
  10.             if current.value > value:
  11.                 previous = current
  12.                 current = current.left  
  13.             else:
  14.                 previous = current
  15.                 current = current.right
  16.         if previous.value > value:
  17.             previous.left = Node(value)
  18.         else:
  19.             previous.right = Node(value)
  20.            
  21.     def in_order_traversal(self):
  22.         current = self
  23.         stack = list()
  24.         while current or len(stack):
  25.             if current:
  26.                 stack.append(current)
  27.                 current = current.left
  28.             else:
  29.                 current = stack.pop()
  30.                 print(current.value)
  31.                 current = current.right
  32.     def print(self):
  33.         self.in_order_traversal()
  34.        
  35. t = Node(1)
  36. t.insert(43)
  37. t.insert(55)
  38. t.insert(18)
  39. t.insert(25)
  40. t.insert(13)
  41. t.insert(3)
  42. t.insert(60)
  43. t.print()
Advertisement
Add Comment
Please, Sign In to add comment