Using a recursive algorithm in C#.
Because this is a pre-order binary tree you must:
- Check the root
- Check the left branches
- Check the right branches
In recursion, we want to establish a base case:
- Where the root == null where we will return 0 as the depth.
- Do work on the left branch, increment the depth counter by 1
- Do work on the right branch, increment the depth counter by 1
- Find the Max depth.
public int MaxDepth(TreeNode root)
{
if(root == null)
{
return 0;
}
int ldepth = 1 + MaxDepth(root.left);
int rdepth = 1 + MaxDepth(root.right);
return Math.Max(ldepth,rdepth);
}