二叉树着色游戏

标签: 深度优先搜索 二叉树

难度: Medium

有两位极客玩家参与了一场「二叉树着色」的游戏。游戏中,给出二叉树的根节点 root,树上总共有 n 个节点,且 n 为奇数,其中每个节点上的值从 1 到 n 各不相同。

最开始时:

  • 「一号」玩家从 [1, n] 中取一个值 x1 <= x <= n);
  • 「二号」玩家也从 [1, n] 中取一个值 y1 <= y <= n)且 y != x

「一号」玩家给值为 x 的节点染上红色,而「二号」玩家给值为 y 的节点染上蓝色。

之后两位玩家轮流进行操作,「一号」玩家先手。每一回合,玩家选择一个被他染过色的节点,将所选节点一个 未着色 的邻节点(即左右子节点、或父节点)进行染色(「一号」玩家染红色,「二号」玩家染蓝色)。

如果(且仅在此种情况下)当前玩家无法找到这样的节点来染色时,其回合就会被跳过。

若两个玩家都没有可以染色的节点时,游戏结束。着色节点最多的那位玩家获得胜利 ✌️。

现在,假设你是「二号」玩家,根据所给出的输入,假如存在一个 y 值可以确保你赢得这场游戏,则返回 true ;若无法获胜,就请返回 false

 

示例 1 :

输入:root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
输出:true
解释:第二个玩家可以选择值为 2 的节点。

示例 2 :

输入:root = [1,2,3], n = 3, x = 1
输出:false

提示:

  • 树中节点数目为 n
  • 1 <= x <= n <= 100
  • n 是奇数
  • 1 <= Node.val <= n
  • 树中所有值 互不相同

Submission

运行时间: 19 ms

内存: 16.1 MB

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:
        q, head = [root], -1
        parent = [None]
        while head + 1 < len(q):
            head += 1
            for node in [q[head].left, q[head].right]:
                if node is not None:
                    q.append(node)
                    parent.append(q[head])
        prev, current = None, None
        for i in range(n):
            if q[i].val == x:
                current = q[i]
                prev = parent[i]
        num_parent = num_parent = self.count_nodes(root) - self.count_nodes(current)
        num_left = self.count_nodes(current.left)
        num_right = self.count_nodes(current.right)
        return num_parent * 2 > n or num_left * 2 > n or num_right * 2 > n

    def count_nodes(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        num_nodes = 1
        if root.left is not None:
            num_nodes += self.count_nodes(root.left)
        if root.right is not None:
            num_nodes += self.count_nodes(root.right)
        return num_nodes

Explain

该题解的核心思路是通过分析三个部分的节点数量来确定第二号玩家是否可以获胜。具体地,这三个部分是:1. 以x为根节点的子树的父节点及其祖先节点;2. x节点的左子树;3. x节点的右子树。如果其中任何一个部分的节点数超过总节点数的一半,那么第二号玩家选择该部分的任意一个节点作为初始着色点,都可以在游戏中取得优势。首先,代码通过层序遍历找到x节点并标记其父节点。然后,分别计算三个部分的节点数,并判断是否有超过总节点数一半的情况。

时间复杂度: O(n)

空间复杂度: O(n)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:
        # 使用层序遍历以找到x节点以及其父节点
        q, head = [root], -1
        parent = [None]
        while head + 1 < len(q):
            head += 1
            for node in [q[head].left, q[head].right]:
                if node is not None:
                    q.append(node)
                    parent.append(q[head])
        prev, current = None, None
        for i in range(n):
            if q[i].val == x:
                current = q[i]
                prev = parent[i]
        # 计算不同部分的节点数
        num_parent = self.count_nodes(root) - self.count_nodes(current)
        num_left = self.count_nodes(current.left)
        num_right = self.count_nodes(current.right)
        # 判断是否有超过总节点数一半的部分
        return num_parent * 2 > n or num_left * 2 > n or num_right * 2 > n

    def count_nodes(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        num_nodes = 1
        if root.left is not None:
            num_nodes += self.count_nodes(root.left)
        if root.right is not None:
            num_nodes += self.count_nodes(root.right)
        return num_nodes

Explore

在层序遍历过程中,我们可以使用一个额外的列表(比如`parent`)来存储每个节点的父节点。对于每个节点`node`,当我们将其子节点添加到队列中时,同时将`node`记录为这些子节点的父节点。因此,当我们访问任何节点时,可以通过索引直接获取其父节点。这种方法确保了每个节点的父节点能够被正确记录并在后续处理中使用。

确实,题解中的`num_parent`计算方式有误,应该包括`x`的父节点及其所有祖先节点的数量。正确的方式是从根节点开始计数,直到`x`节点,然后从总节点数`n`中减去`x`节点的子树节点数。这样,我们可以使用`n - self.count_nodes(current)`来得到`x`节点的父节点及其祖先节点的数量。这会包括整棵树的节点数减去`x`及其所有子节点的数量。

递归函数`count_nodes`在原始题解中并没有使用备忘录化,这可能导致对于重复子结构的多次计算,从而增加算法的时间复杂度。为了优化,我们可以使用一个哈希表(或字典)作为备忘录,来存储每个节点的子树节点数。这样,当计算一个节点的子树节点数时,首先检查这个节点是否已经在备忘录中计算过,如果是,则直接返回存储的值,否则进行计算并存储。这样可以显著减少重复计算,提高算法效率。