题目描述:
思路:
/**
* 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 res=0;
void dfs(TreeNode* root,int sum){
if(root==NULL)
return ;
//到达叶子节点,一条路径和计算完成,加入到最终结果中
if(root->left==NULL&&root->right==NULL)
res+=sum;
//左子树不空,深入一层则*2
if(root->left)
dfs(root->left,sum*2+root->left->val);
//右子树不空,深入一层*2
if(root->right)
dfs(root->right,sum*2+root->right->val);
}
int sumRootToLeaf(TreeNode* root) {
if(root==NULL)
return 0;
dfs(root,root->val);
return res;
}
};