662. Maximum Width of Binary Tree

class Solution:


def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
q,res=[],0
if root:
q=[root]
res = self.func(q)
return res

def func(self,q):
max_=0
while(q):
size = len(q)
left=-1
right=0
for i in range(size):
front=q.pop(0)
if front==None:
q.append(None)
q.append(None)
else:
if left==-1:
left=i
right=i
q.append(front.left)
q.append(front.right)
all_false=1
for i in q:
if i!=None:
all_false=0
break
if all_false:
q=[]
max_=max(max_,right-left)

return max_+1
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
q=[(root,0)]
max_width=1
while(q):
size = len(q)
max_width= max(max_width,q[-1][1] - q[0][1] + 1)
for i in range(size):
node,pos=q.pop(0)
if node.left:
q.append((node.left,2*pos+1))

if node.right:
q.append((node.right,2*pos+2))
return max_width

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.