Sum root to leaf numbers
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
.
Thought: There are three situations: 1. The current node is empty, 0. 2. The leaf node is returned, and the current value is returned. 3. The parent node is returned, and the sum of the left and right path values is returned.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ int dfs(TreeNode *root, int sum) { if(root == 0) return 0; sum = sum * 10 + root->val; if(root->left || root->right) return dfs(root->left, sum) + dfs(root->right, sum); return sum; }class Solution {public: int sumNumbers(TreeNode *root) { return dfs(root, 0); }};
23. Sum root to leaf numbers