Skip to content

Commit 108ddcd

Browse files
committed
Added solution to find sum from root to leaf in tree
1 parent 56817b6 commit 108ddcd

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
package com.eprogrammerz.examples.algorithm.trees;
2+
3+
import org.junit.Test;
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
import static org.junit.Assert.assertEquals;
9+
10+
/**
11+
* Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
12+
*
13+
* An example is the root-to-leaf path 1->2->3 which represents the number 123.
14+
*
15+
* Find the total sum of all root-to-leaf numbers % 1003.
16+
*
17+
* Example :
18+
*
19+
* 1
20+
* / \
21+
* 2 3
22+
* The root-to-leaf path 1->2 represents the number 12.
23+
* The root-to-leaf path 1->3 represents the number 13.
24+
*
25+
* Return the sum = (12 + 13) % 1003 = 25 % 1003 = 25
26+
*
27+
*/
28+
public class SumRoot2Leaf {
29+
public int sumNumbers(TreeNode root) {
30+
List<Integer> sumToLeafs = new ArrayList<>();
31+
findSumToLeaf(root, sumToLeafs, 0);
32+
return sumToLeafs.stream().mapToInt(i -> i).sum() % 1003;
33+
}
34+
35+
private void findSumToLeaf(TreeNode node, List<Integer> sumToLeafs, int sum) {
36+
if (node == null) return;
37+
38+
if (node.left == null && node.right == null) {
39+
sumToLeafs.add(sum * 10 + node.val);
40+
return;
41+
}
42+
findSumToLeaf(node.left, sumToLeafs, sum * 10 + node.val);
43+
findSumToLeaf(node.right, sumToLeafs, sum * 10 + node.val);
44+
}
45+
46+
@Test
47+
public void testSumNumbers() {
48+
System.out.println(1938 % 1003);
49+
/**
50+
* 6
51+
* / \
52+
* 3 7
53+
* / \ \
54+
* 2 5 1
55+
* \
56+
* 1
57+
*/
58+
TreeNode root = new TreeNode(6);
59+
root.left = new TreeNode(3);
60+
root.right = new TreeNode(7);
61+
62+
root.right.right = new TreeNode(1);
63+
64+
root.left.left = new TreeNode(2);
65+
root.left.right = new TreeNode(5);
66+
67+
// ((632) + (635) + (671)) % 1003
68+
// 1938 % 1003
69+
// 935
70+
assertEquals(935, sumNumbers(root));
71+
72+
// add right node to rightest node on last level
73+
root.right.right.right = new TreeNode(1);
74+
assertEquals(957, sumNumbers(root));
75+
76+
}
77+
78+
@Test
79+
public void testSumNumbers1() {
80+
System.out.println(512 % 1003);
81+
/**
82+
* 5
83+
* /
84+
* 1
85+
* /
86+
* 2
87+
*
88+
*
89+
*/
90+
TreeNode root = new TreeNode(5);
91+
root.left = new TreeNode(1);
92+
93+
root.left.left = new TreeNode(2);
94+
// (512) % 1003
95+
// 512
96+
assertEquals(512, sumNumbers(root));
97+
}
98+
}

0 commit comments

Comments
 (0)