dev_el
dev_el

Reputation: 2947

Leetcode 104 Maximum Depth of Binary Tree

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?

Upvotes: 0

Views: 337

Answers (3)

lupz
lupz

Reputation: 3638

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.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386578

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));
    };

Upvotes: 0

jonasdev
jonasdev

Reputation: 736

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.

Upvotes: 1

Related Questions