问题:根节点到叶子结点的所有权值和
分析:从根节点遍历,若遍历到叶子结点,则sum+其路径的所有权值和
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int sum; void dfs(TreeNode *root,int num) { if(root->left==NULL && root->right==NULL) sum+=num; if(root->left) dfs(root->left,num*10+root->left->val); if(root->right) dfs(root->right,num*10+root->right->val); } int sumNumbers(TreeNode *root) { if(root==NULL) return 0; sum=0; int num=0; dfs(root,root->val); return sum; } };