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
.
1->3
represents the number 13
. Return the sum = 12 + 13 = 25
.
简单的用递归就可以实现,代码如下:
1 class Solution { 2 public: 3 int sumNumbers(TreeNode* root) { 4 dfs(root, 0); 5 } 6 7 int dfs(TreeNode * root, int curr){ 8 if(!root) 9 return 0;10 if(!root->left && !root->right)11 return curr * 10 + root->val;12 return dfs(root->left, curr * 10 + root->val) + dfs(root->right, curr * 10 + root->val);13 }14 };
java版本的代码如下所示:
1 public class Solution { 2 public int sumNumbers(TreeNode root) { 3 return dfs(root, 0); 4 } 5 6 public int dfs(TreeNode root, int curr){ 7 if(root == null) 8 return 0; 9 if(root.left == null && root.right == null)10 return curr * 10 + root.val;11 return dfs(root.left, curr * 10 + root.val) + dfs(root.right, curr * 10 + root.val);12 }13 }