/**
* 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) {}
* };
*/classSolution{private:int res;public:intlongestUnivaluePath(TreeNode* root){
res =0;dfs(root);return res;}intdfs(TreeNode* root){if(!root)return0;if(!root->left &&!root->right)return0;int left =dfs(root->left), right =dfs(root->right);int left1 =0, right1 =0;if(root->left && root->left->val == root->val){
left1 =left +1;}if(root->right && root->right->val == root->val){
right1 = right +1;}
res =max(res, left1 + right1);returnmax(left1, right1);}};
997. 找到小镇的法官
代码实现(自解)
classSolution{public:intfindJudge(int n, vector<vector<int>>& trust){
vector<int>in(n +1);
vector<int>out(n +1);for(auto& v : trust){
out[v[0]]++;
in[v[1]]++;}for(int i =1; i <= n; i++){if(!out[i]&& in[i]== n -1)return i;}return-1;}};
1557. 可以到达所有点的最少点数目
代码实现(部分看题解)
classSolution{public:
vector<int>findSmallestSetOfVertices(int n, vector<vector<int>>& edges){
vector<int>in(n);for(auto& v : edges) in[v[1]]++;
vector<int> ans;for(int i =0; i < n; i++){if(!in[i]) ans.push_back(i);}return ans;}};