Created
August 12, 2017 19:19
-
-
Save sdpatil/a3be17f5c33855dea3d76b6bb461daf4 to your computer and use it in GitHub Desktop.
Sum the root-to-leaf paths in a binary tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Problem: Design an algorithm to compute the sum of the binary numbers represented by the the | |
| * root-to-leaf path | |
| */ | |
| public class SumRootToLeafPaths { | |
| public int sumRootToLeaf(BinaryTreeNode<Integer> tree) { | |
| return sumRootToLeafHelper(tree, 0); | |
| } | |
| public int sumRootToLeafHelper(BinaryTreeNode<Integer> tree, int partialPathSum) { | |
| if (tree == null) | |
| return 0; | |
| partialPathSum = partialPathSum * 2 + tree.data; | |
| if (tree.left == null && tree.right == null) { | |
| return partialPathSum; | |
| } | |
| return sumRootToLeafHelper(tree.left, partialPathSum) + | |
| sumRootToLeafHelper(tree.right, partialPathSum); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment