Subtree Removal Game with Fibonacci Tree Problem
Description
LeetCode Problem 2005.
A Fibonacci tree is a binary tree created using the order function order(n):
order(0)is the empty tree.order(1)is a binary tree with only one node.order(n)is a binary tree that consists of a root node with the left subtree asorder(n - 2)and the right subtree asorder(n - 1).
Alice and Bob are playing a game with a Fibonacci tree with Alice staring first. On each turn, a player selects a node and removes that node and its subtree. The player that is forced to delete root loses.
Given the integer n, return true if Alice wins the game or false if Bob wins, assuming both players play optimally.
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
Example 1:

Input: n = 3
Output: true
Explanation:
Alice takes the node 1 in the right subtree.
Bob takes either the 1 in the left subtree or the 2 in the right subtree.
Alice takes whichever node Bob doesn't take.
Bob is forced to take the root node 3, so Bob will lose.
Return true because Alice wins.
Example 2:

Input: n = 1
Output: false
Explanation:
Alice is forced to take the root node 1, so Alice will lose.
Return false because Alice loses.
Example 3:

Input: n = 2
Output: true
Explanation:
Alice takes the node 1.
Bob is forced to take the root node 2, so Bob will lose.
Return true because Alice wins.
Constraints:
1 <= n <= 100
Solution
Approach: Sprague-Grundy Values
This is an impartial game: both players have the same moves, and the loser is whoever has to remove the root. We can compute a Grundy value for each Fibonacci tree and Alice wins exactly when the value of order(n) is not zero.
A single node has Grundy value 0: its only move removes the root, which loses, so there is no useful move. For a larger tree, a move removes some node in one of the two subtrees. The Grundy value of a root with subtrees of values a and b (each removal inside a subtree acts like a game where the subtree root is also removable) is (a + 1) xor (b + 1), where an empty subtree counts as 0 rather than a + 1.
For the Fibonacci tree, order(n) has order(n - 1) as its right subtree and order(n - 2) as its left one, which is empty for n = 2. With g[i] the Grundy value of order(i):
g[1] = 0;g[2] = g[1] + 1 = 1;g[i] = (g[i - 1] + 1) xor (g[i - 2] + 1)fori >= 3.
Return g[n] != 0. (The pattern is periodic, and the result turns out to be n % 6 != 1.)
Complexity: O(n) time and O(n) space.
class Solution:
def findGameWinner(self, n: int) -> bool:
# g[i] is the Grundy value of the Fibonacci tree of order i
g = [0] * (n + 2)
for i in range(2, n + 1):
# the right subtree always exists; the left one is empty only for i == 2
g[i] = (g[i - 1] + 1) ^ ((g[i - 2] + 1) if i > 2 else 0)
return g[n] != 0