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.
classNode:def__init__(self,info):self.info=infoself.left=Noneself.right=Noneself.level=Nonedef__str__(self):returnstr(self.info)defheight(root):ifrootisNone:return0returnmax(1+height(root.left),1+height(root.right))definOrder(root):ifroot==None:returninOrder(root.left)print(str(root.info)+'(BF='+str(height(root.left)-height(root.right))+')',end=" ")inOrder(root.right)defpreOrder(root):ifroot==None:returnprint(str(root.info)+'(BF='+str(height(root.left)-height(root.right))+')',end=" ")preOrder(root.left)preOrder(root.right)defturnRight(t):x=t.lefty=x.rightt.left=yx.right=treturnxdefturnLeft(t):x=t.righty=x.leftt.right=yx.left=treturnxdefswap(root):root.ht=height(root.left)-height(root.right)ifroot.ht>1:ifroot.left:rlt=height(root.left.left)-height(root.left.right)ifrlt<0:root.left=turnLeft(root.left)returnturnRight(root)ifroot.ht<-1:ifroot.right:rrt=height(root.right.left)-height(root.right.right)ifrrt>0:root.right=turnRight(root.right)returnturnLeft(root)returnrootclassBinarySearchTree:def__init__(self):self.root=None#Node is defined as#self.left (the left child of the node)#self.right (the right child of the node)#self.info (the value of the node)definsert(self,val):#Enter you code here.def_insert(root,val):ifrootisNone:returnNode(val)ifval<root.info:root.left=_insert(root.left,val)ifval>root.info:root.right=_insert(root.right,val)returnswap(root)self.root=_insert(self.root,val)tree=BinarySearchTree()t=int(input())arr=list(map(int,input().split()))k=int(input())arr.append(k)foriinrange(t+1):tree.insert(arr[i])inOrder(tree.root)print()preOrder(tree.root)
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 →
Python