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.
还是不大习惯递归,总是本能地去用非递归的方法。不过这题还是递归比较简单好写。把到当前节点为止的sum作为参数进行传递。遇到leaf的话就把sum*10+node.val返回。sum*10就是这题的要点了。
这里有一个比较详尽的想法。
/**
* 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) {
if(root == null)
return 0;
return sumNumbers(root, 0);
}
public int sumNumbers(TreeNode node, int sum){
if(node == null)
return 0;
if(node.left == null && node.right == null)
return sum * 10 + node.val;
return sumNumbers(node.left, sum * 10 + node.val) + sumNumbers(node.right, sum * 10 + node.val);
}
}

本文介绍了一种使用递归算法解决二叉树中所有从根节点到叶子节点的路径所代表数字之和的问题。通过将当前路径的数值作为参数传递,当遇到叶子节点时返回该路径对应的数值。
8362

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



