imashutosh51

Fixing Two nodes of a BST

Aug 4th, 2022 (edited)
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. '''
  2. Brute force: get the inorder or the tree in an array and then sort the array and traverse the tree again paralleley with the array, replace the element of the node when it is not matching with the ith element of the array.
  3. '''
  4.  
  5. '''
  6. Logic:
  7. Inorder of BST is always sorted.
  8. If only one node will be swapped in a BST then there is only two possibility:
  9.  
  10. case1:
  11. eg Inorder: 3 25 7 8 10 15 20 5 swapped nodes(ie. 25, 5) are not adjacent
  12. here the current node ie. 7  is lesser than previous node,ie. 25 so make left=25,middle=7
  13. and again 5 is lesse than 20 so make left=5.
  14. if there is left,middle and right then swap(left,right);
  15.  
  16. case 2:swapped nodes are adjacent
  17. eg. 3 5 8 7 10 15 20 25
  18. swapped node(ie. 8,7)
  19. using previous case left=8 and middle=7.
  20. no voilation or sorted order again,so no right node so,swap(left,middle)
  21.  
  22. '''
  23. '''
  24. class Node:
  25.    def __init__(self, val):
  26.        self.right = None
  27.        self.data = val
  28.        self.left = None
  29. '''
  30. def fun(root,dict):
  31.     if root:
  32.         fun(root.left,dict)
  33.         if dict['prev'] and root.data<dict['prev'].data and dict['left']:
  34.             dict['right']=root
  35.         elif dict['prev'] and root.data<dict['prev'].data:
  36.             dict['left']=dict['prev']
  37.             dict['middle']=root
  38.         dict['prev']=root
  39.         fun(root.right,dict)
  40.            
  41. class Solution:
  42.     def correctBST(self, root):
  43.         dict={'middle':None, 'left':None, 'right':None, 'prev':None}
  44.         fun(root,dict)
  45.         if dict['right']:
  46.             dict['left'].data,dict['right'].data=dict['right'].data,dict['left'].data
  47.         else:
  48.             dict['left'].data,dict['middle'].data=dict['middle'].data,dict['left'].data
  49.         return root
  50.            
Advertisement
Add Comment
Please, Sign In to add comment