原題連結:6057. 統計值等于子樹平均值的節點數

自己在考場上寫的:
/**
* 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 {
public:
int Count(TreeNode* root)
{
if(!root) return 0;
else if(!root->left && !root->right) return 1;
else return Count(root->left)+Count(root->right)+1;
}
int sum(TreeNode* root)
{
if(!root) return 0;
else if(!root->left && !root->right) return root->val;
else return sum(root->left)+sum(root->right)+root->val;
}
int averageOfSubtree(TreeNode* root) {
queue<TreeNode* > q;
q.push(root);
int res=0;
while(!q.empty())
{
root=q.front(); q.pop();
if(sum(root)/Count(root)==root->val) res++;
if(root->left) q.push(root->left);
if(root->right) q.push(root->right);
}
return res;
}
};
參考别人的更簡潔好看的代碼:
繼續練!
/**
* 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 {
public:
int res=0;
pair<int,int> dfs(TreeNode* root)
{
int x=1,y=root->val;
if(root->left)
{
auto z=dfs(root->left);
x+=z.first; y+=z.second;
}
if(root->right)
{
auto z=dfs(root->right);
x+=z.first; y+=z.second;
}
if(y/x==root->val) res++;
return {x,y};
}
int averageOfSubtree(TreeNode* root) {
dfs(root);
return res;
}
};