You really just need to code it and try it - you will learn so much. (Editing: I certainly ...)
I believe the source code does not work for hasPathSum(tree, 7) , because node 2 is not a leaf.
Edit:
The original code was shot due to obvious errors - obviously, at least for everyone except me :-)
Edit:
My new solution is below. Please note that the included optimization ( if (sum <= node.data) ) assumes that the tree is composed of all positive values. It must be deleted or changed if the tree has zero or negative data values. (thanks @Mark Peters).
Also take a look at the discussion of comments on the hasPathSum(null, 0) processing hasPathSum(null, 0) .
static boolean hasPathSumBert(final Node node, final int sum) { // return true if we run out of tree and sum==0 if (node == null) { // empty tree // choose one: return (sum == 0); //return false; } else if (node.left == null && node.right == null) { // leaf return (sum == node.data); } else if (sum <= node.data) { // sum used up return false; } else { // try children return (node.left != null && hasPathSumBert(node.left, sum - node.data)) || (node.right != null && hasPathSumBert(node.right, sum - node.data)); } }
Full code:
public class TreeTest { static class Node { int data; Node left; Node right; Node(final int data, final Node left, final Node right) { this.data = data; this.left = left; this.right = right; } } public static void main(final String[] args) { final Node three = new Node(3, null, null); final Node two = new Node(2, three, null); final Node one = new Node(1, null, null); final Node five = new Node(5, two, one); final Node tree = five; for (int i = 0; i <= 10; i++) { System.out.println(i + ""); System.out.println("original = " + hasPathSum(tree, i)); System.out.println("bert = " + hasPathSumBert(tree, i)); System.out.println("mark = " + hasPathSumMark(tree, i)); System.out.println(); } System.out.println("hasPathSumBert(null, 0): "+ hasPathSumBert(null, 0)); System.out.println("hasPathSumBert(null, 1): "+ hasPathSumBert(null, 1)); } static boolean hasPathSum(final Node node, final int sum) {
Run example: (Case with record 7)
0 original = false bert = false mark = false 1 original = false bert = false mark = false 2 original = false bert = false mark = false 3 original = false bert = false mark = false 4 original = false bert = false mark = false 5 original = false bert = false mark = false 6 original = true bert = true mark = true 7 original = true bert = false mark = false 8 original = false bert = false mark = false 9 original = false bert = false mark = false 10 original = true bert = true mark = true hasPathSumBert(null, 0): true hasPathSumBert(null, 1): false