直接遍历所有路径将结果加起来即可。 优化空间有限、
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int sum=0;
public int sumNumbers(TreeNode root) {
if( root == null )
{
return sum;
}
fun( root,0 );
return sum;
}
void fun(TreeNode root,int tmp)
{
tmp = tmp*10+root.val;
if(root.left==null && root.right==null)
{
sum += tmp;
return ;
}
if( root.left != null )
{
fun(root.left,tmp);
}
if( root.right != null )
{
fun(root.right,tmp);
}
return ;
}
}
202

被折叠的 条评论
为什么被折叠?



