您的位置:首页 > 其它

比较两颗二叉树是否相等

2009-12-23 20:21 274 查看
比较两颗可以旋转的二叉树是否相等,二叉树的左右子节点可以旋转,比如可以把二叉树的左节点旋转成为右节点,右节点旋转成为左节点。

欢迎博友讨论。我的程序是用递归的思想去做。

struct BinaryNode
{
int m_iValue;
BinaryNode * m_pLeft;
BinaryNode * m_pRight;
};

bool IsEqual(BinaryNode* currentLeft, BinaryNode* currentRight)
{
//如果两个节点都是空
if(currentLeft==NULL && currentRight==NULL)
{
return 1;
}
//如果一个空一个非空
if(!currentLeft||!currentRight)
{
return 0;
}
//exit point
if(currentLeft->m_pLeft==NULL && currentLeft->m_pRight==NULL && currentRight->m_pLeft==NULL && currentRight->m_pRight==NULL)
{
return (currentLeft->m_iValue==currentRight->m_iValue);
}
else
{
//check left right child 递归来做
if(currentLeft->m_iValue==currentRight->m_iValue)
{
if(IsEqual(currentLeft->m_pLeft,currentRight->m_pLeft)&&IsEqual(currentLeft->m_pRight,currentRight->m_pRight))
{
return 1;
}
else if(IsEqual(currentLeft->m_pLeft,currentRight->m_pRight)&&IsEqual(currentLeft->m_pRight,currentRight->m_pLeft))
{
return 1;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: