[LeetCode]Sum Root to Leaf Numbers
发布日期:2021-11-22 02:49:01 浏览次数:2 分类:技术文章

本文共 784 字,大约阅读时间需要 2 分钟。

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.

public class Solution {    public int sumNumbers(TreeNode root) {				if(root == null)			return 0;		return sumNumber(root,"0");	}	private int sumNumber(TreeNode root, String s) {			if(root.left ==null && root.right ==null){			return Integer.valueOf(s+root.val);		}		return (root.left != null ?sumNumber(root.left, s+root.val):0)+(root.right != null?sumNumber(root.right, s+root.val):0);	}}
参考:

转载地址:https://blog.csdn.net/zxdfc/article/details/48787523 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:[LeetCode]Binary Search Tree Iterator
下一篇:[LeetCode]Remove Duplicates from Sorted Array II

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月17日 15时21分30秒