We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importsyslines=[]forlineinsys.stdin:if'Exit'==line.rstrip():breaklines.append(line.split('\n')[0])nol=lines[0]treeInput=[int(x)forxinlines[1].split(' ')]toIns=lines[2]# print(nol)# print(treeInput)# print(toIns)classNode:def__init__(self,data):self.data=dataself.left=Noneself.right=Noneself.height=1#Initially,newnodeshaveheight1classAVLTree:def__init__(self):self.root=None# Insertion operation - Add your code heredefinsert(self,data):self.root=insertnew(self.root,data)# Traversalsdefinorder(self,node):ifnodeisnotNone:self.inorder(node.left)print(f"{node.data}(BF={getBalance(node)})",end=" ")self.inorder(node.right)defpostorder(self,node):ifnodeisnotNone:print(f"{node.data}(BF={getBalance(node)})",end=" ")self.postorder(node.left)self.postorder(node.right)# Function to print BF at each nodedefprint_balance(self):self.inorder(self.root)print("")self.postorder(self.root)definsertnew(root,data):ifrootisNone:returnNode(data)ifroot.data<data:root.right=insertnew(root.right,data)ifroot.data>data:root.left=insertnew(root.left,data)root.height=1+max(getheight(root.left),getheight(root.right))# left left caseifgetBalance(root)>1anddata<root.left.data:returnrotateright(root)# right right caseifgetBalance(root)<-1anddata>root.right.data:returnrotateleft(root)# left right caseifgetBalance(root)>1androot.left.data<data:root.left=rotateleft(root.left)returnrotateright(root)# right left caseifgetBalance(root)<-1androot.right.data>data:root.right=rotateright(root.right)returnrotateleft(root)returnrootdefgetheight(root):ifrootisNone:return0returnroot.heightdefgetBalance(root):ifrootisNone:return0return(getheight(root.left)-getheight(root.right))defrotateleft(root):y=root.rightT2=y.left# perform rotationy.left=rootroot.right=T2root.height=1+max(getheight(root.left),getheight(root.right))y.height=1+max(getheight(y.left),getheight(y.right))returnydefrotateright(root):y=root.leftT3=y.right# perform rotationy.right=rootroot.left=T3root.height=1+max(getheight(root.left),getheight(root.right))y.height=1+max(getheight(y.left),getheight(y.right))returnytree=AVLTree()forxintreeInput:tree.insert(x)tree.insert(int(toIns))tree.print_balance()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Self Balancing Tree
You are viewing a single comment's thread. Return to all comments →
Fully working python solution