Problem:
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.
Explanation:
给出一棵树,将其每条路径所经过的结点的数值分别累加,并计算总和。
My Thinking:
通过递归,将每条路径累计数值保存在sum中,并在叶子结点时加入totalsum
My Solution:
class Solution {
public int sumNumbers(TreeNode root) {
return recursive(root,0,0);
}
public int recursive(TreeNode root,int sum,int totalsum){
if(root==null)
return totalsum;
if(root.left==null && root.right==null)//到叶子结点时加入总和
return totalsum+sum*10+root.val;
totalsum=recursive(root.left,sum*10+root.val,totalsum);
totalsum=recursive(root.right,sum*10+root.val,totalsum);
return totalsum;
}
}
Optimum Thinking:
基于递归,将totalsum去除,直接将左路径和右路径的总和返回即可。
Optimum Solution:
class Solution {
public int sumNumbers(TreeNode root) {
return recursive(root,0);
}
public int recursive(TreeNode root,int sum){
if(root==null)
return 0;
if(root.left==null && root.right==null)
return sum*10+root.val;
return recursive(root.left,sum*10+root.val)+recursive(root.right,sum*10+root.val);
}
}