Given a binary tree containing digits from0-9Only, each root-to-leaf path
Cocould represent a number.
An example is the root-to-leaf path1->2->3Which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path1->2Represents the number12.
The root-to-leaf path1->3Represents the number13.
Return the sum = 12 + 13 =25.
Solution:
Traverse the binary tree to know the number of root-to-leaf nodes. Because the data is weak, the number on the path is used
Int can be saved. For example, if the depth of a fruit tree is greater than 10, int will overflow. Therefore, it is better to use a string,
Then simulate the addition operation.
Solution code:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void dfs(TreeNode *rt,int path,int &sum) { if (!rt) return ; path = path * 10 + rt->val ; if (rt->left == rt->right && !rt->left) sum +=path; dfs(rt->left,path,sum); dfs(rt->right,path,sum); } int sumNumbers(TreeNode *root) { int ans = 0 ; dfs(root,0,ans); return ans ; }};