第一次写的解法,。对于只有一个儿子的节点重复了两次 。。结果就弄复杂了。。
我也觉得不应该能有这么多的重复嘛
<span style="font-size:18px;">/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
package javaTrain;
public class Train9 {
public int sum = 0;
public int sumNumbers(TreeNode root) {
if(root == null) return sum;
sum = dfs(root.left,root.val)+dfs(root.right,root.val);
return sum;
}
private int dfs(TreeNode root,int num){
if(root == null) return num;
return dfs(root.left,num*10+root.val) + dfs(root.right,num*10+root.val);
}
}
</span>
调整后的正解,唉~边界要想清楚呀。。
<span style="font-size:18px;">/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumNumbers(TreeNode root) {
return helper(root,0);
}
private int helper(TreeNode root, int sum)
{
if(root == null)
return 0;
if(root.left==null && root.right==null)
return sum*10+root.val;
return helper(root.left,sum*10+root.val)+helper(root.right,sum*10+root.val);
}
}</span>
【LeetCode】 Sum Root to Leaf Numbers
原文地址:http://blog.csdn.net/ymzmdx/article/details/44347511