Given a Binary Tree Containing digits from0-9
Only, each root-to-leaf path cocould represent a number.
An example is the root-to-leaf path1->2->3
Which represents the number123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / 2 3
The root-to-leaf path1->2
Represents the number12
.
The root-to-leaf path1->3
Represents the number13
.
Return the sum = 12 + 13 =25
.
Starting from the root node, the concept of DFS is actually postorder (first-order traversal). The process of traversing the value on the path is multiplied by the base 10 every time. The Code is as follows:
class Solution {public: int sum; void dfs(TreeNode *root, int pre){ if (root == NULL) return; int current = root->val + 10 * pre; if (root->left == NULL && root->right == NULL){ sum += current; return; } if (root->left) dfs(root->left, current); if (root->right) dfs(root->right, current); } int sumNumbers(TreeNode *root) { sum = 0; dfs(root, 0); return sum; }};