First Thoughts: base case of recursion when node is leaf (node.left is null and node.right is null, or node is null), pass counter through argument, while keep adding one every time one call is made. Since return cannot return two counters, only keep the maximum of the two counts, because we're only interested in the maximum depth.
My Solution:
class Solution {
public int maxDepth(TreeNode root) {
if (root==null) return 0;
int counter = doWork(root, 1);
return counter;
}
public int doWork(TreeNode root, int counter) {
if (root==null) return counter;
if (root.left==null && root.right==null) return counter;
int leftCount = doWork(root.left, counter+1);
int rightCount = doWork(root.right, counter+1);
return Math.max(leftCount, rightCount);
}
}
Passing accumulator variable throughout, while incrementing by one every time it goes through the function is effective
Storing the values into variables are one way to pass by one return property
Returning the maximum of the two keeps track of only the maximum count