I have an incorrect BST where two nodes are not in the right position. I know that inorder traversal of a BST is sorted. Hence I traverse through the tree with three pointers : first, last, middle. If the current node is less than previous node, I set previous node as first and current node as middle. This is for the first violation. When second violation occurs, I assign last as current node. Now when last is NULL
, swap first and middle and when last is not NULL
swap first and last. This is what I have done:
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def fixBST(root,first,middle,last,prev):
if( root ):
fixBST( root.left, first, middle, last, prev )
if (prev and root.data < prev.data):
if ( first is None ):
first = prev
middle = root
else:
last = root
prev = root
fixBST( root.right, first, middle, last, prev )
return (first,middle,last)
def correctBST( root ):
first = middle = last = prev = None
first,middle,last = fixBST( root, first, middle, last, prev )
if( first and last ):
t = first.data
first.data = last.data
last.data = t
elif( first and middle ):
t = first.data
first.data = middle.data
middle.data = t
def printInorder(node):
if (node == None):
return
printInorder(node.left)
print node.data
printInorder(node.right)
root = Node(6)
root.left = Node(10)
root.right = Node(2)
root.left.left = Node(1)
#root.left.right = Node(3)
#root.right.right = Node(12)
#root.right.left = Node(7)
print "Inorder Traversal of the original tree \n"
printInorder(root)
correctBST(root)
print "\nInorder Traversal of the fixed tree \n"
printInorder(root)
I get the same incorrect tree after printing inorder traversal the second time. I believe the first, middle, last values are not getting stored? Am I missing out on something?
EDIT: I edited the code. But still the return value of first, middle and last is None. Is it not the right way?