C# Recursive Solution and explaination


  • 0
    R

    Using a recursive algorithm in C#.
    Because this is a pre-order binary tree you must:

    1. Check the root
    2. Check the left branches
    3. Check the right branches

    In recursion, we want to establish a base case:

    1. Where the root == null where we will return 0 as the depth.
    2. Do work on the left branch, increment the depth counter by 1
    3. Do work on the right branch, increment the depth counter by 1
    4. 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); 
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.