I am writing a program to get Sum of depth for a given binaryTree. It's returning proper value with instance value but returning wrong value(greater than expected) if I am printing the returned value from the method. Code with output is as below.
Note: I am having the right solution also but I am posting this solution to understand what wrong happing with the call stack of the recursion. My expectation was in the last stack memory the final value will persist that will be returned to the caller method it returning a different value.
public class NodeDepth_2 {
static int sum = 0;
public static int nodeDepths(BinaryTree root) {
Integer depthSum = 0;
Integer depth = -1;
int finalValue = nodeDepths(root, depth, depthSum);
System.out.println("Printing returned value from method: " + finalValue);
System.out.println("sum from instance variable : " + sum);
return depthSum.intValue();
}
public static int nodeDepths(BinaryTree root, int depth, int depthSum) {
depth = depth + 1;
depthSum = depthSum + depth;
sum = sum + depth;
if (root.left == null && root.right == null) {
return depthSum;
}
return nodeDepths(root.left, depth, depthSum) + nodeDepths(root.right, depth, depthSum);
}
static class BinaryTree {
int value;
BinaryTree left;
BinaryTree right;
public BinaryTree(int value) {
this.value = value;
left = null;
right = null;
}
}
public static void main(String[] args) {
BinaryTree root = new BinaryTree(1);
root.left = new BinaryTree(2);
root.left.left = new BinaryTree(4);
root.left.left.left = new BinaryTree(8);
root.left.left.right = new BinaryTree(9);
root.left.right = new BinaryTree(5);
root.right = new BinaryTree(3);
root.right.left = new BinaryTree(6);
root.right.right = new BinaryTree(7);
nodeDepths(root);
}
}
Output is:
Printing returned value from method: 21 // wrong value returned with method return
sum from instance variable : 16 // this is expected value