Algorithms and Data Structures · Middle · Question 38 of 75

How do you compute the maximum depth of a binary tree recursively?

function depth(node) {
  if (!node) return 0;
  // ?
}

Explanation

The depth of a node is one more than the deeper of its subtrees, and an empty subtree has depth 0. Adding both subtrees would count nodes, not depth. The cost is O(n), with recursion depth equal to the height.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 38

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz