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
.
解题思路:
这题我采用的是递归的方法,按照题目的描述,每遇到一次分岔路就会衍生出两个数相加,于是我就利用递归,从二叉树的最底分支开始相加,一层层往上叠加,最终得到所求的数。
代码:
1 /** 2 * Definition for a binary tree node. 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 pathSum(TreeNode* root, int sum){ 13 if(!root) 14 //空节点返回0 15 return 0; 16 if(!root->left && !root->right) 17 //到最底节点 18 return sum*10+root->val; 19 return pathSum(root->left, sum*10+root->val)+pathSum(root->right, sum*10+root->val); //存在至少一个节点 20 } 21 int sumNumbers(TreeNode* root) { 22 return pathSum(root, 0); 23 } 24 };