Iam_Sandeep

Minimum Swaps To Convert Binary Tree Into BST

Mar 12th, 2022
1,439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.57 KB | None | 0 0
  1. link="https://www.codingninjas.com/codestudio/problems/minimum-swaps-to-convert-binary-tree-into-bst_1118109?leftPanelTab=1"
  2. def minimumSwaps(arr: list, n: int):
  3.     res=[]
  4.     def inorder(i):
  5.         if i>=n:return
  6.         inorder(2*i+1)
  7.         res.append(arr[i])
  8.         inorder(2*i+2)
  9.     inorder(0)
  10.     count=0
  11.     i=0
  12.     items=[(j,i) for i,j in enumerate(res)]
  13.     items.sort()
  14.    
  15.     while i<n:
  16.         if items[i][1]==i:i+=1
  17.         else:
  18.             y=items[i][1]
  19.             items[i],items[y]=items[y],items[i]
  20.             count+=1
  21.     return count
  22.  
Advertisement
Add Comment
Please, Sign In to add comment