1145. 二叉树着色游戏

题目链接:1145. 二叉树着色游戏

方法:分类

解题思路

(1)\(x\) 节点将二叉树分成了 \(3\) 部分,分别是父节点子树、左子树、右子树(节点数分别为 n1 n2 n3);
2023-02-03 11-51-40 创建的截图.png
(2)为了使得二号玩家染色尽可能的多,应该让 \(y\) 选择在 \(x\) 相邻的节点。若存在以下一种情况,则二号玩家稳赢,n1 > n2 + n3 + 1 || n2 > n1 + n3 + 1 || n3 > n1 + n2 + 1

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    TreeNode* player1_start;
public:
    void preorder(TreeNode* root, int x) {
        if (root->val == x) {
            player1_start = root;
            return ;
        }

        if (root->left != nullptr) preorder(root->left, x);
        if (root->right != nullptr) preorder(root->right, x);

        return ;
    }

    int levelorder(TreeNode* root) {
        int cnt = 0;
        queue<TreeNode*> q;
        q.push(root);
        cnt ++ ;
        while (!q.empty()) {
            TreeNode* front = q.front();
            q.pop();
            if (front->left != nullptr) {
                q.push(front->left);
                cnt ++ ;
            }
            if (front->right != nullptr) {
                q.push(front->right);
                cnt ++ ;
            }
        }

        return cnt;
    }

    bool btreeGameWinningMove(TreeNode* root, int n, int x) {
        preorder(root, x);
        int n1, n2, n3; 
        if (player1_start->left == nullptr) n2 = 0;
        else n2 = levelorder(player1_start->left);

        if (player1_start->right == nullptr) n3 = 0;
        else n3 = levelorder(player1_start->right);

        n1 = n - n2 - n3 - 1;

        if (n1 > n2 + n3 + 1 || n2 > n1 + n3 + 1 || n3 > n1 + n2 + 1) return true;
        else return false;
    }
};
posted @ 2023-04-06 22:17  lixycc  阅读(21)  评论(0)    收藏  举报