题目: 有两位极客玩家参与了一场「二叉树着色」的游戏。游戏中,给出二叉树的根节点 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

相关文章: