您的位置:首页 > 其它

LeetCode Sum Root to Leaf Numbers

2015-09-07 22:29 260 查看
原题链接在这里:https://leetcode.com/problems/sum-root-to-leaf-numbers/

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
.

本题与Path Sum II相似。

DFS, 终止条件都是左右child都是空,否则cur*10加child.val, 递归调用函数,回来时除以10.

Note:1. helper 是pass by value, 所以res一定要用个array存储。

2. 递归调用后需要去掉尾节点,本题中除以10即可。

3. root == null 的corner case 是在主函数里单独讨论, dfs里不需要重复讨论。

Time Complexity: O(n). Space: O(h), h是树的高度.

AC Java:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumNumbers(TreeNode root) {
if(root == null){
return 0;
}

int [] res = new int[1];

int cur = root.val;
dfs(root, cur, res);
return res[0];
}

private void dfs(TreeNode root, int cur, int [] res){
if(root.left == null && root.right == null){
res[0] += cur;
return;
}

if(root.left != null){
cur = cur*10 + root.left.val;
dfs(root.left, cur, res);
cur /= 10;
}

if(root.right != null){
cur = cur*10 + root.right.val;
dfs(root.right, cur, res);
cur /= 10;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: