题目描述:
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.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
1
/ \
2 3
Output: 25
Explanation:The root-to-leaf path 1->2represents the number 12.The root-to-leaf path 1->3the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.The root-to-leaf path 4->9->1represents the number 491.
The root-to-leaf path 4->0 represents the number 40.Therefore, sum = 495 + 491 + 40 = 1026.
思路:递归的方法
从根节点开始递归的计算每条路径的路径和,并进行累加。
递归截止的条件:
若当前节点为空,则返回sum为0;若当前节点不为空,其左右节点为空,则返回当前计算出的当前路径和。
实现(递归):
实现1:
- 首先是先序遍历,每遍历到一个节点,如果该节点不是null,用传进来的sum * 10 + 当前节点的值
sum = sum * 10 + root.val;
当当前节点是叶子节点,返回sum,这就是一条路径的值。这是递归的子问题
- 递归左、右子树,返回左右子树的值的和。
public int sumNumbers2(TreeNode root) {
return dfs(root,0);
}
public int dfs(TreeNode root,int sum){
if(root==null){
return 0;
}
int currSum=sum*10+root.val;
if(root.left==null&&root.right==null){
return currSum;
}
return dfs(root.left,currSum)+dfs(root.right,currSum);
}
实现2:
int total=0;
public int sumNumbers(TreeNode root) {
helper(root,0);
return total;
}
private void helper(TreeNode root,int sum){
if(root==null) return;
sum=sum*10+root.val;
if(root.left==null&&root.right==null){
total+=sum;
return;
}
helper(root.left,sum);
helper(root.right,sum);
}
思路2:迭代
用两个堆栈,一个用来记录当前遍历到的节点,另外一个栈用来记录节点路径。压栈和我们遍历的顺序相反,先压右节点,再压左节点,如果当前节点的左右子节点均为空,则表明已经到达叶子节点,此时我们把这条路径的路径和加入到结果和中。然后再次从栈中弹出下一个节点值继续上述判断,直到栈为空。
实现:
public int sumNumbers3(TreeNode root) {
if(root==null){
return 0;
}
Stack<TreeNode> s=new Stack<>();
Stack<String> path=new Stack<>();
s.push(root);
path.push(""+root.val);
int sum=0;
while(!s.isEmpty()){
TreeNode node=s.pop();
String currentPath=path.pop();
if(node.right!=null){
s.push(node.right);
path.push(currentPath+(""+node.right.val));
}
if(node.left!=null){
s.push(node.left);
path.push(currentPath+(""+node.left.val));
}
if(node.left==null&&node.right==null){
sum=sum+Integer.valueOf(currentPath);
}
}
return sum;
}