C# Recursive approach with MaxHeight helper method.


  • 0
    S
    public bool IsBalanced(TreeNode node) 
    {
        if(node == null)
            return true;
        int leftHeight = MaxDepthOfTree(node.left);
        int rightHeight = MaxDepthOfTree(node.right);
    
        if(Math.Abs(leftHeight - rightHeight) > 1)
            return false;
        else
            return IsBalanced(node.left) && IsBalanced(node.right);
    }
    private int MaxDepthOfTree(TreeNode currentNode)
    {
        if(currentNode == null)
            return 0;
        return 1 + Math.Max(MaxDepthOfTree(currentNode.left), MaxDepthOfTree(currentNode.right));
    }

Log in to reply
 

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