1145二叉树着色游戏

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

来源: https://leetcode-cn.com/problems/binary-tree-coloring-game/

法一: 自己的代码

思路: 用迭代方法,先找到一号玩家着色的第一个节点,再计算该节点左子树和右子树的节点个数.好处是寻找第一个节点的过程无需遍历每个节点.而用递归的方法则需要.

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
# 执行用时 :36 ms, 在所有 python3 提交中击败了89.41% 的用户
# 内存消耗 :12.8 MB, 在所有 python3 提交中击败了100.00%的用户
class Solution:
    def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:
        # 用于计算某个节点下面有多少个节点
        def count_node(root):
            cou = 0
            # 注意要先判断是否为空
            if root is None:
                return cou
            queue = []
            queue.append(root)
            while queue:
                a = queue.pop(0)
                cou += 1
                if a.left:
                    queue.append(a.left)
                if a.right:
                    queue.append(a.right)
            return cou
        # 寻找一号玩家第一次着色的节点
        def find_x(root, x):
            queue = []
            queue.append(root)
            while queue:
                a = queue.pop(0)
                if a.val == x:
                    return a
                if a.left:
                    queue.append(a.left)
                if a.right:
                    queue.append(a.right)
        x_root = find_x(root,x)
        # 分别计算一号玩家第一次着色节点的左子树和右子树节点的个数
        x_left_count = count_node(x_root.left)
        x_right_count = count_node(x_root.right)
        # 注意这里要减一
        if max(x_left_count,x_right_count,n-x_left_count-x_right_count-1) > int((n-1)/2):
            return True
        else:
            return False
if __name__  == '__main__':
    duixiang = Solution()
    a = duixiang.btreeGameWinningMove(root,n,x)
View Code

法二: https://leetcode-cn.com/problems/binary-tree-coloring-game/solution/shen-du-you-xian-sou-suo-python3-by-smoon1989-3/

思路: 遍历每一个节点.返回结果,方法非常类似于236二叉树的最近公共祖先中的递归方法,本方法实际上提供了一个二叉树递归方法加入返回值的模板.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:
        self.red_left, self.red_right = 0, 0
        
        def dfs(root):
            if not root:
                return 0
            left = dfs(root.left)
            right = dfs(root.right)
            if root.val == x:
                self.red_left = left
                self.red_right = right
            return left + right + 1
        
        dfs(root)
        parent = n - self.red_left - self.red_right - 1
        judge = [parent, self.red_left, self.red_right]
        return any([j > n // 2 for j in judge])
View Code
原文地址:https://www.cnblogs.com/xxswkl/p/12068016.html