LeetCode OJ:Sum Root to Leaf Numbers(根到叶节点数字之和)

时间:2022-04-13 21:20:01

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.

简单的用递归就可以实现,代码如下:

 class Solution {
public:
int sumNumbers(TreeNode* root) {
dfs(root, );
} int dfs(TreeNode * root, int curr){
if(!root)
return ;
if(!root->left && !root->right)
return curr * + root->val;
return dfs(root->left, curr * + root->val) + dfs(root->right, curr * + root->val);
}
};

java版本的代码如下所示:

 public class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, );
} public int dfs(TreeNode root, int curr){
if(root == null)
return ;
if(root.left == null && root.right == null)
return curr * + root.val;
return dfs(root.left, curr * + root.val) + dfs(root.right, curr * + root.val);
}
}