原题网址:https://leetcode.com/problems/sum-root-to-leaf-numbers/
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.
方法:递归。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int sum;
private void sum(TreeNode root, int current) {
current *= 10;
current += root.val;
if (root.left == null && root.right == null) {
sum += current;
return;
}
if (root.left != null) {
sum(root.left, current);
}
if (root.right != null) {
sum(root.right, current);
}
}
public int sumNumbers(TreeNode root) {
if (root == null) return 0;
sum = 0;
sum(root, 0);
return sum;
}
}

本文介绍了一个LeetCode上的题目,即求给定只包含0-9数字的二叉树中所有从根节点到叶子节点路径所表示数字的总和。通过递归方法实现了算法,并给出了具体实现代码。
2983

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



