[Leetcode 39] 129 Sum Root to Leaf Numbers
Problem:
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
Analysis:
Simple tree DFS problem.
Code:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int sumNumbers(TreeNode *root) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 if (root == NULL) return 0; 16 17 int pathSum = 0, total = 0; 18 helper(root, pathSum, total); 19 20 return total; 21 } 22 23 int helper(TreeNode *node, int pathSum, int& total) { 24 if (node->left==NULL && node->right==NULL) { 25 total += pathSum*10 + node->val; 26 } 27 28 pathSum = pathSum*10 + node->val; 29 if(node->left != NULL) 30 helper(node->left, pathSum, total); 31 32 if (node->right != NULL) 33 helper(node->right, pathSum, total); 34 } 35 36 };
Attention: