Learner Level
Implement the maximumDepthBinaryTree method that returns the maximum depth of a binary tree.
The input contains a binary tree represented as an integer array tree and its length size. The values are arranged in level-order format.
Your task is to return the maximum depth of the tree. The maximum depth is the number of nodes on the longest path from the root node down to a leaf node.
For example, the tree [3,9,20,0,0,15,7] has maximum depth 3.
Use recursion to calculate the height of each subtree.
For any node, calculate the depth of its left subtree and right subtree. The depth of the current node is 1 + max(leftDepth, rightDepth). If the index is outside the array or represents a missing node, its depth is 0.
The value returned for the root node is the maximum depth of the whole tree.
Pseudocode:
function maximumDepthBinaryTree(tree, size):
return depth(0)
function depth(index):
if index >= size or tree[index] is missing:
return 0
leftDepth = depth(2 * index + 1)
rightDepth = depth(2 * index + 2)
return 1 + max(leftDepth, rightDepth)