Maximum Depth of Binary Tree

To find the maximum depth of a binary tree, we can use recursion. First, we need to check if the tree is empty. If not, we need to find the maximum depth of the left and right subtrees. The maximum depth of the tree is the maximum of the left and right subtrees' depths, plus one.

Problem

Given a binary tree, find the maximum depth of the tree.
Example input:
    1
   / \
  2   3
     / \
    4   5
Example output:
3

Solution

This solution is in C#. Our A.I. can create solutions in multiple languages.
by kayakane
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterviewQuestions.LeetCode
{
    class MaximumDepthOfBinaryTree
    {
        /// <summary>
        /// Given a binary tree, find its maximum depth.
        /// The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public static int MaxDepth(TreeNode root)
        {
            if (root == null)
            {
                return 0;
            }

            int leftDepth = MaxDepth(root.left);
            int rightDepth = MaxDepth(root.right);

            return Math.Max(leftDepth, rightDepth) + 1;
        }
    }
}

A.I. Evaluation of the Solution

The candidate's solution correctly finds the maximum depth of a binary tree. The solution uses a recursive approach, which is a good approach for this problem. The solution is clear and easy to understand.

Evaluated at: 2022-11-30 14:15:28