mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
java: add «129. Sum Root to Leaf Numbers»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
1711b319be
commit
badc57445c
1 changed files with 22 additions and 0 deletions
22
java/sum-root-to-leaf-numbers.java
Normal file
22
java/sum-root-to-leaf-numbers.java
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
class Solution {
|
||||||
|
private boolean isLeaf(TreeNode node) {
|
||||||
|
return node != null && node.left == null && node.right == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int sumNumbers(TreeNode node, int number) {
|
||||||
|
if (node == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
number = 10 * number + node.val;
|
||||||
|
if (isLeaf(node)) {
|
||||||
|
return number;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sumNumbers(node.left, number) + sumNumbers(node.right, number);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int sumNumbers(TreeNode root) {
|
||||||
|
return sumNumbers(root, 0);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue