boolcheckPerfectNumber(int num) { if (num == 0) returnfalse; int n = 0; for (int i = 1; i * i <= num; i++) { if (num % i == 0) { n += i; if (i * i != num) n += num / i; } } return num == n; }
stringreverseStr(string s, int k) { for (int i = 0; i * 2 * k < s.length(); i++) { int start = i * 2 * k; int temp = (i + 1) * 2 * k; int end = (temp + start) / 2; if (end > s.length()) end = s.length(); reverse(s.begin() + start, s.begin() + end); } return s; }
解题思路:任意一条路径可以被写成两个箭头(不同方向),每个箭头代表一条从某些点向下遍历到孩子节点的路径。假设我们知道对于每个节点最长箭头距离分别为 L, R,那么最优路径经过 L + R + 1 个节点。 按照常用方法计算一个节点的深度:max(depth of node.left, depth of node.right) + 1。在计算的同时,经过这个节点的路径长度为 1 + (depth of node.left) + (depth of node.right) 。搜索每个节点并记录这些路径经过的点数最大值count,期望长度是 count - 1。
// @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
classSolution { public:
int dia = 0;
inttravel(TreeNode *node) { if (node == NULL) return0; int L = travel(node->left); int R = travel(node->right); dia = max(dia, L + R + 1); return1 + max(L, R); }
intdiameterOfBinaryTree(TreeNode *root) { if (root == NULL) return0; travel(root); return dia - 1; }
boolcheckRecord(string s) { int A = 0; int L = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == 'A') A++; if (s[i] == 'L') L++; elseif (L <= 2) L = 0; } return A <= 1 && L <= 2; }