Skip to content

Commit 17c876e

Browse files
solves sum of root to leaf binary numbers
1 parent 87975d3 commit 17c876e

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@
276276
| 1013 | [Partition Array into Three Parts with equal Sum](https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum) | | |
277277
| 1018 | [Binary Prefix Divisible by 5](https://leetcode.com/problems/binary-prefix-divisible-by-5) | [![Java](assets/java.png)](src/BinaryPrefixDivisibleBy5.java) | |
278278
| 1021 | [Remove Outermost Parenthesis](https://leetcode.com/problems/remove-outermost-parentheses) | [![Java](assets/java.png)](src/RemoveOutermostParentheses.java) | |
279-
| 1022 | [Sum of Root to Leaf Binary Numbers](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers) | | |
279+
| 1022 | [Sum of Root to Leaf Binary Numbers](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers) | [![Java](assets/java.png)](src/SumOfRootToLeafBinaryNumbers.java) | |
280280
| 1025 | [Divisor Game](https://leetcode.com/problems/divisor-game) | | |
281281
| 1029 | [Two City Scheduling](https://leetcode.com/problems/two-city-scheduling) | | |
282282
| 1030 | [Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order) | | |

src/SumOfRootToLeafBinaryNumbers.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
public class SumOfRootToLeafBinaryNumbers {
2+
public int sumRootToLeaf(TreeNode root) {
3+
return sumRootToLeaf(root, 0);
4+
}
5+
6+
private int sumRootToLeaf(TreeNode root, int sum) {
7+
if (root == null) return 0;
8+
if (root.left == null && root.right == null) return sum + root.val;
9+
return sumRootToLeaf(root.left, (sum + root.val) << 1) + sumRootToLeaf(root.right, (sum + root.val) << 1);
10+
}
11+
}

0 commit comments

Comments
 (0)