Skip to content

Instantly share code, notes, and snippets.

@sdpatil
Created August 12, 2017 19:19
Show Gist options
  • Select an option

  • Save sdpatil/a3be17f5c33855dea3d76b6bb461daf4 to your computer and use it in GitHub Desktop.

Select an option

Save sdpatil/a3be17f5c33855dea3d76b6bb461daf4 to your computer and use it in GitHub Desktop.
Sum the root-to-leaf paths in a binary tree
/**
* 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