Maximum Width of Binary Tree | Leet code 662 | Theory explained + Python code | July code challenge

preview_player
Показать описание
This video is a solution to Leet code 662, Maximum Width of Binary Tree. I first give a theoretical explanation and then I go over its Python implementation.

Comment below if you have a better solution to this problem!

Let me know if you have any feedback and don't forget to subscribe for more videos!

Gear used:
Рекомендации по теме
Комментарии
Автор

This math was interesting, good explanation

srib
Автор

Nice solution but you dont actually need the temp_q since you can just iterate through the length of the q. So this would work essentially

class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
if not root: return None

q = [(root, 0)]
width = 1

while q:

if len(q) > 1:
width = max(width, q[-1][1] - q[0][1] + 1)

for _ in range(len(q)):
node, position = q.pop(0)
if node.left != None:
q.append((node.left, 2*position))

if node.right != None:
q.append((node.right, 2*position + 1))

return width

dayal
Автор

Thanks Anish for this awesome explanation

vidyutphagetra
join shbcf.ru