Пример #1
0
        private static Nullable <int> BalancedHeightRecursive(BinaryTreeNode <int> node)
        {
            if (node == null)
            {
                return(-1);
            }

            Nullable <int> leftHeight = IsHeightBalanced.BalancedHeightRecursive(node.Left);

            if (leftHeight == null)
            {
                return(null);
            }

            Nullable <int> rightHeight = IsHeightBalanced.BalancedHeightRecursive(node.Right);

            if (rightHeight == null)
            {
                return(null);
            }

            if (Math.Abs(rightHeight.Value - leftHeight.Value) > 1)
            {
                return(null);
            }

            return(Math.Max(rightHeight.Value, leftHeight.Value) + 1);
        }
Пример #2
0
        private static bool BalancedHeightBruteForce(BinaryTreeNode <int> node)
        {
            if (node == null)
            {
                return(true);
            }

            if (!IsHeightBalanced.BalancedHeightBruteForce(node.Left))
            {
                return(false);
            }

            if (!IsHeightBalanced.BalancedHeightBruteForce(node.Right))
            {
                return(false);
            }

            int leftHeight  = node.Left == null ? -1 : node.Left.Data;
            int rightHeight = node.Right == null ? -1 : node.Right.Data;

            if (Math.Abs(leftHeight - rightHeight) > 1)
            {
                return(false);
            }

            node.Data = Math.Max(leftHeight, rightHeight) + 1;

            return(true);
        }
Пример #3
0
 private static bool Recursive(BinaryTreeNode <int> root)
 {
     return(IsHeightBalanced.BalancedHeightRecursive(root) != null);
 }
Пример #4
0
 private static bool BruteForce(BinaryTreeNode <int> root)
 {
     return(IsHeightBalanced.BalancedHeightBruteForce(root));
 }