Approach: Use postorder traversal.
public bool IsBalanced()
{
if (this.Root == null)
{
return true;
}
int height = 0;
return this.IsBalanced(this.Root, ref height);
}
private bool IsBalanced(BinaryTreeNode node, ref int height)
{
if (node == null)
{
height = 0;
return true;
}
int lHeight = 0, rHeight = 0;
bool isLeftTreeBalanced = this.IsBalanced(node.LeftNode, ref lHeight);
bool isRightTreeBalanced = this.IsBalanced(node.RightNode, ref rHeight);
height = Math.Max(lHeight, rHeight) + 1;
if (Math.Abs(lHeight - rHeight) > 1)
{
return false;
}
return isLeftTreeBalanced && isRightTreeBalanced;
}
No comments:
Post a Comment