[leetcode] 662. Maximum Width of Binary Tree @ python

本文探讨了如何求解二叉树的最大宽度,通过两种不同的方法实现:使用deque和列表进行BFS遍历,每层节点按序号计算宽度,最终得出最大宽度。示例展示了不同二叉树结构下最大宽度的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

Example 1:
Input:

       1
     /   \
    3     2
   / \     \  
  5   3     9 

Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
Example 2:
Input:

      1
     /  
    3    
   / \       
  5   3     

Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).
Example 3:
Input:

      1
     / \
    3   2 
   /        
  5      

Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).
Example 4:
Input:

      1
     / \
    3   2
   /     \  
  5       9 
 /         \
6           7

Output: 8
Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).

解法1

我们假设树是完全二叉树, 这样可以对每个节点计数, 我们设根节点的序号为1, 在第n个节点时, 它的左子树是第2n个节点, 它的右子树是2n+1个节点, 然后使用BFS, 如果子树存在的话, 将序号放入列表中, 宽度是 = 最右边的序号 - 最左边的序号 + 1, 每次循环时更新res. 我们使用deque存放每层节点.
Time: O(n)
Space: O(n)

代码

class Solution:
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        # base case
        if not root: return 0
        q = collections.deque()
        q.append((root, 1))
        res = 0
        while q:
            width = q[-1][1] - q[0][1] + 1
            res = max(res, width)
            for i in range(len(q)):
                node, count = q.popleft()
                if node.left:
                    q.append((node.left, 2*count))
                if node.right:
                    q.append((node.right, 2*count + 1))
                    
        return res

解法2

同解法1, 使用列表存放每层的节点

代码

class Solution:
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        # base case
        if not root: return 0
        q = [(root, 1)]
        res = 0
        while q:
            width = q[-1][1] - q[0][1] + 1
            res = max(res, width)
            new_q = []
            for tup in q:
                node, count = tup[0], tup[1]
                if node.left:
                    new_q.append((node.left, 2*count))
                if node.right:
                    new_q.append((node.right, 2*count + 1))
            q = new_q
                    
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值