题目描述
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.

方法思路
class Solution {
//Memory Usage: 36.7 MB, less than 85.40%
//Runtime: 0 ms, faster than 100.00%
public int sumNumbers(TreeNode root) {
return sum(root, 0);
}
public int sum(TreeNode node, int x){
if(node == null) return 0;
if(node.left == null && node.right == null)
return node.val + x * 10;
int left = sum(node.left, node.val + x * 10);
int right = sum(node.right, node.val + x * 10);
return left + right;
}
}

本文介绍了一种解决二叉树中所有从根节点到叶子节点路径数字之和的方法。通过递归算法,将每个路径转换为数字并计算总和。此算法在内存使用和运行时间上表现出色。
384

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



