0

I am reviewing the solution to this leetcode problem. The solution is the following:

var maxDepth = function(root) {
  let maxNode = (node, sum) => {
    if (node === null) {
      return sum;
    }
    return Math.max(maxNode(node.left, sum + 1), maxNode(node.right, sum + 1));
  }
  return maxNode(root, 0);  
};

I was wondering why return maxNode(root, 0); must include a return. Is it required to 'activate' the inner function? If so, why doesn't just maxNode(root, 0) just 'activate' it?

1
  • It'll be an infinite loop otherwise. A function calling itself for an infinite number of times. A return with conditions prevents it from running forever when that condition is met. Go read about recursive functions. Commented Aug 19, 2020 at 7:10

3 Answers 3

1

The solution includes "recursion", which means the maxNode function is called multiple times from within itself. This requires the maxNode function to return a value to it's calling "instance". The maxDepth function has a return statement to return the calculated maxNode value.

Sign up to request clarification or add additional context in comments.

Comments

0

This function maxDepth will determine the maximum depth of a binary tree.

You would use it like this:

let depth = maxDepth(treeRoot);

Without the return, the function will determine the depth but you will not get the result when you call the function.

Comments

0

It is a another construction of a recursive function by taking a sum as parameter for a recursion.

It could be easily rewritten to the below function where the adding of one is outside of the function call.

var maxDepth = function(node) {
        if (!node) return 0;
        return 1 + Math.max(maxNode(node.left), maxNode(node.right));
    };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.