129. Sum Root to Leaf Numbers

网友投稿 579 2022-10-09

129. Sum root to Leaf Numbers

129. 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; } * } */class Solution { public int sumNumbers(TreeNode root) { if (root == null) return 0; if (root.left == null && root.right == null) return root.val; if (root.left != null) { root.left.val = root.val * 10 + root.left.val; } if (root.right != null) { root.right.val = root.val * 10 + root.right.val; } return sumNumbers(root.left) + sumNumbers(root.right); } }

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public int sumNumbers(TreeNode root) { return sumNumbers(root, 0); } private int sumNumbers(TreeNode root, int number) { if (root == null) { return 0; } else if (isLeaf(root)) { return number * 10 + root.val; } else { return sumNumbers(root.left, number * 10 + root.val) + sumNumbers(root.right, number * 10 + root.val); } } private boolean isLeaf(TreeNode root) { return root.left == null && root.right == null; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:详解netty中的frame解码器
下一篇:React-Native淘宝客APP小程序
相关文章

 发表评论

暂时没有评论,来抢沙发吧~