LeetCode 662. Maximum Width of Binary Tree - 二叉树(Binary Tree)系列题13

Given the root of a binary tree, return the maximum width of the given tree.

The maximum width of a tree is the maximum width among all levels.

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

It is guaranteed that the answer will in the range of 32-bit signed integer.

Example 1:

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

Example 2:

LeetCode 662. Maximum Width of Binary Tree - 二叉树(Binary Tree)系列题13_第1张图片

Input: root = [1,3,null,5,3]
Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).

Example 3:

LeetCode 662. Maximum Width of Binary Tree - 二叉树(Binary Tree)系列题13_第2张图片

Input: root = [1,3,2,5]
Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).

Constraints:

  • The number of nodes in the tree is in the range [1, 3000].
  • -100 <= Node.val <= 100

题目要求一棵二叉树的最大宽度。树的每一层都有一个宽度,即从那一层最左边的节点到最右边节点的长度,计算长度时也要包括它们之间的空节点。树的最大宽度就是二叉树所有层中最大的那个宽度。

如果熟悉如何用一个数组来表示一棵二叉树,那这题就相当简单了。从根节点开始按水平遍历的顺序把节点放入数组中(中间遇到的空节点也要被当成一个节点在数组中有一个位置),这样每个节点都在数组中对应一个位置,要是一个节点在数组中的索引为index,那么它的两个子节点在数组中的位置就应该是2*index + 1, 和2*index + 2。知道了索引值之后,那么每一层的宽度就取决于那一层最左边节点和最右边节点对应在数组中的索引值,二者相减加1就是宽度。

因此本题的解法就是在我们所熟悉的水平遍历算法的基础上给每个节点引入一个索引值,如果用BFS法的话,就是放入队列中的单元是(节点,索引值)。(根节点的索引值为0)。

class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        res = 0
        q = deque()
        
        q.append((root, 0))
        
        while q:
            n = len(q)
            start, end = 0, 0
            for i in range(n):
                node, index = q.popleft()
                if i == 0:
                    start = index
                elif i == n - 1:
                    end = index
                res = max(res, end - start + 1)
                if node.left:
                    q.append((node.left, 2 * index + 1))
                if node.right:
                    q.append((node.right, 2 * index + 2))
        
        return res

 

你可能感兴趣的:(二叉树(Binary,Tree),Leetcode刷题笔记,leetcode,算法,数组结构,python,二叉树)