Take the problem of finding the maximum depth of a binary tree as an example. (A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.)
The following code is part of the codes. With each recursive call, the value of depth
is modified by depth++
of the function at the previous level, but when the function ends and returns to the function at the previous level, there is no need to perform a depth--
and even a depth+=100
could run perfectly.
IntelliJ will prompt that "the value changed at depth += 100
will never be used". This line will be executed neverthless, yet the the changing is in vain.
So what happened in the JVM? How many times has the variable depth
actually been created in the stack memory? Is a new int depth
created every time the function is called? Or do all functions have variables that point to the same int depth
? If the former, then I think depth--
should be necessary, and if the latter, then I think each time you go to the next level of recursion, the depth
passed in can only be 0. So now I am confused.
This is my first question in stackoverflow, and my English is not as good as a native speaker. I Hope my description is clear enough. Thanks to anyone who cares about this question, and I appreciate your help!
public static void max(TreeNode root,int depth){
if(root == null) return;
depth ++
max(root.left,depth);
max(root.right,depth);
depth += 100;
}