LeetCode: Deepest Leaves Sum C# Given a binary tree, return the sum of values of its deepest leaves.

    


  Constraints:
  
  The number of nodes in the tree is between 1 and 10^4. The value of
  nodes is between 1 and 100.


Please review for performance and style 

using GraphsQuestions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    /// &lt;summary&gt;
    /// https://leetcode.com/problems/deepest-leaves-sum/
    /// &lt;/summary&gt;

    [TestClass]
    public class DeepestLeavesSumTest
    {
        [TestMethod]
        public void ExampleTest()
        {
            var root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.left.left = new TreeNode(4);
            root.left.right = new TreeNode(5);
            root.left.left.left = new TreeNode(7);
            root.right = new TreeNode(3);
            root.right.right = new TreeNode(6);
            root.right.right.right = new TreeNode(8);
            DeepestLeavesSumClass deepest = new DeepestLeavesSumClass();
            Assert.AreEqual(15, deepest.DeepestLeavesSum(root));
        }
    }

    public class DeepestLeavesSumClass
    {

        int maxDepth = 0;
        int sum = 0;
        public int DeepestLeavesSum(TreeNode root)
        {
            if (root == null)
            {
                return 0;
            }
            DFS(root, 0);
            return sum;
        }

        private void DFS(TreeNode root, int depth)
        {
            if (root == null)
            {
                return;
            }
            if (maxDepth &lt; depth + 1)
            {
                maxDepth = depth + 1;
                sum = root.val;
            }
            else if (depth + 1 == maxDepth)
            {
                sum += root.val;
            }
            DFS(root.left, depth + 1);
            DFS(root.right, depth + 1);
        }
    }

}
Rename DFS to DeepestLeavesSum.

Extract  depth + 1 to variable. 

In here else if (depth + 1 == maxDepth) the else is reduant.

The order of depth + 1 and maxDepth is different between the Ifs. One time  maxDepth is on the left side and other time on the right side.

Usually, when writing recursion, you return the value and not store it in the class. 

If you call DeepestLeavesSum twice with the same object the second call will return wrong results because it will use sum and maxDepth of the first call. A good practice is avoiding saving state.