/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { int l, r; // return the number of node in subtree intdfs(TreeNode* root, int x){ if (root == nullptr) return0; int left = dfs(root->left, x); int right = dfs(root->right, x); if (root->val == x) { l = left; r = right; } return left + right + 1; } public: boolbtreeGameWinningMove(TreeNode* root, int n, int x){ dfs(root, x); if (n == l + r + 1) { return l != r; } else { int parent = n - l - r - 1; return parent - 1 > l + r || l - 1 > r + parent || r - 1 > l + parent; } } };
/** * Your SnapshotArray object will be instantiated and called as such: * SnapshotArray* obj = new SnapshotArray(length); * obj->set(index,val); * int param_2 = obj->snap(); * int param_3 = obj->get(index,snap_id); */
classSolution { boolequal(const string& text, int begin1, int end1, int begin2, int end2){ if (end1 - begin1 != end2 - begin2) { returnfalse; } for (int i = 0; i < end1 - begin1; ++i) { if (text[begin1 + i] != text[begin2 + i]) returnfalse; } returntrue; } intrecurse(const string& text, int begin, int end){ if (begin == end) return0; for (int i = 1; begin + i <= end - i; ++i) { if (equal(text, begin, begin + i, end - i, end)) { returnrecurse(text, begin + i, end - i) + 2; } } return1; } public: intlongestDecomposition(string text){ returnrecurse(text, 0, text.size()); } };