Facebook
From Mammoth Crane, 4 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 128
  1. class Node:
  2.     def __init__(self,val):
  3.         self.right=None
  4.         self.left=None
  5.         self.val=val
  6.  
  7. def insert(root,node):
  8.     if root is None:
  9.         root=node
  10.     else:
  11.         if root.val>node.val:
  12.             if root.left is None:
  13.                 root.left=node
  14.             else:
  15.                 insert(root.left,node)
  16.         else:
  17.             if root.right is None:
  18.                 root.right=node
  19.             else:
  20.                 insert(root.right,node)
  21.  
  22. def find_min(root,parent):
  23.     if root.left:
  24.         return find_min(root.left,root)
  25.     else:
  26.         return[parent,root]
  27.  
  28. def del_node(root,val):
  29.     if root.val == val:
  30.         if root.right and root.left:
  31.             [parent,succ] = find_min(root.right,root)
  32.             if parent.left == succ:
  33.                 parent.left=succ.right
  34.             else:
  35.                 parent.right = succ.right
  36.             succ.left=root.left
  37.             succ.right=root.right
  38.             return succ
  39.         else:
  40.             if root.left:
  41.                 return root.left
  42.             if root.right:
  43.                 return root.right
  44.     else:
  45.         if root.val>val:
  46.             if root.left:
  47.                 root.left=del_node(root.left,val)
  48.         else:
  49.             if root.right:
  50.                 root.right=del_node(root.right,val)
  51.         return root
  52.  
  53. def inorder(root):
  54.     if root:
  55.         inorder(root.left)
  56.         print(root.val)
  57.         inorder(root.right)
  58.  
  59. def preorder(root):
  60.     if root:
  61.         print(root.val)
  62.         preorder(root.left)
  63.         preorder(root.right)
  64.  
  65. def postorder(root):
  66.     if root:
  67.         postorder(root.left)
  68.         postorder(root.right)
  69.         print(root.val)
  70.  
  71. print('Inserting values in a tree')
  72. root=Node(50)
  73. insert(root,Node(30))
  74. insert(root,Node(20))
  75. insert(root,Node(40))
  76. insert(root,Node(70))
  77. insert(root,Node(60))
  78. insert(root,Node(80))
  79.  
  80. print('pre order traversal')
  81. preorder(root)
  82. print('post order traversal')
  83. postorder(root)
  84.  
  85.  
  86. root=del_node(root,80)
  87. print('After deleting')
  88. preorder(root)
  89.  
  90.        
  91.