< Summary

Information
Class: LeetCode.Algorithms.BalancedBinaryTree.BalancedBinaryTreeDepthFirstSearch
Assembly: LeetCode
File(s): D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\BalancedBinaryTree\BalancedBinaryTreeDepthFirstSearch.cs
Line coverage
100%
Covered lines: 16
Uncovered lines: 0
Coverable lines: 16
Total lines: 51
Line coverage: 100%
Branch coverage
100%
Covered branches: 8
Total branches: 8
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
IsBalanced(...)100%22100%
IsBalanced(...)100%66100%

File(s)

D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\BalancedBinaryTree\BalancedBinaryTreeDepthFirstSearch.cs

#LineLine coverage
 1// --------------------------------------------------------------------------------
 2// Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv).
 3// All Rights Reserved.
 4// --------------------------------------------------------------------------------
 5// This software is the confidential and proprietary information of Eugene Eremeev
 6// (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not
 7// disclose such Confidential Information and shall use it only in accordance with
 8// the terms of the license agreement you entered into with Eugene Eremeev (also
 9// known as Yevhenii Yeriemeieiv).
 10// --------------------------------------------------------------------------------
 11
 12using LeetCode.Core.Models;
 13
 14namespace LeetCode.Algorithms.BalancedBinaryTree;
 15
 16/// <inheritdoc />
 17public class BalancedBinaryTreeDepthFirstSearch : IBalancedBinaryTree
 18{
 19    /// <summary>
 20    ///     Time complexity - O(n)
 21    ///     Space complexity - O(log n) for a balanced tree, O(n) for a skewed tree
 22    /// </summary>
 23    /// <param name="root"></param>
 24    /// <returns></returns>
 25    public bool IsBalanced(TreeNode? root)
 726    {
 727        return root == null || IsBalanced(root, out _);
 728    }
 29
 30    private static bool IsBalanced(TreeNode? root, out int height)
 7431    {
 7432        if (root == null)
 4033        {
 4034            height = 0;
 35
 4036            return true;
 37        }
 38
 3439        var leftIsBalanced = IsBalanced(root.left, out var leftHeight);
 3440        var rightIsBalanced = IsBalanced(root.right, out var rightHeight);
 41
 3442        height = 1 + Math.Max(leftHeight, rightHeight);
 43
 3444        if (!leftIsBalanced || !rightIsBalanced)
 145        {
 146            return false;
 47        }
 48
 3349        return Math.Abs(leftHeight - rightHeight) <= 1;
 7450    }
 51}