Suppose I have a recursive function that works on a perfectly balanced binary tree with n
nodes and height log(n)
and call the function below on the root of the tree.
void printPaths(TreeNode root, int[] array, int depth){
if (root == null){
print array;
}
array[depth] = root.data;
printPaths(root.left, array, depth + 1);
printPaths(root.right, array, depth + 1);
}
array = new int[depthOfTree]
printPaths(root, array, 0);
Let the array be length log(n)
(it will store the values along the tree's paths). I know the recursion call stack will be max height log(n)
. What I'm unsure of is how the "pass-by-value" nature of Java and the Java garbage collection come into play to affect the time and space complexity.
1) What is the time complexity of passing the array to a recursive call? If Java is "pass-by-value," does each recursive call take O(log(n))
to simply copy the array before starting any function execution?
2) What is the upper bound of how many of these array copies are floating around in memory at any one time? My inclination is to say O(log(n))
. Does that mean the space complexity is O(log(n)log(n))
? I've read in a book that "the space complexity is O(log(n))
since the algorithm will recurse O(log(n))
times and the path parameter is only allocated once at O(log(n))
space during the recursion".