AcWing 3766. 二叉树的带权路径长度
原题链接
简单
作者:
Bear_King
,
2022-02-13 11:20:50
,
所有人可见
,
阅读 241
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int dfs(TreeNode* root, int depth){
if(!root) return 0;
if(!root->left && !root->right) return root->val * depth;
return dfs(root->left,depth + 1) + dfs(root->right, depth + 1);
}
int pathSum(TreeNode* root) {
return dfs(root,0);
}
};