i am trying to learn abit about recursive methods and is writing a method for my binary tree that counts the sum of all the integers in the tree my code works fine and all but i am still abit confused about how the application knows when to stop. my code looks like the this:
public int sum() {
return sum(overallRoot);
}
private int sum(IntTreeNode root) {
if (root == null) {
return 0;
} else {
return root.data + sum(root.left) + sum(root.right);
}
}
(the above code is from my nodeTree class)
The next code is from my main class:
public class TreeClient {
/**
* @param args
*/
public static void main(String[] args) {
IntTree tree = new IntTree(12);
System.out.println(tree.sum());
}
}
So the question is (maybe for many quite simple) but how does my application know when to stop? ive tried with simple system out prints to figur out but as far as my understanding is right now the method would call it self in an endless loop?
hope someone has time to respond!
In any recursive program, your iteration stops when a base condition
is reached.. Here your base condition is : -
if (root == null) {
return 0;
}
So, when your root.left
and root.right
, in the following return
statement in else block both becomes null, you have reached your base condition
, and hence your loop stops..
return root.data + sum(root.left) + sum(root.right);