您的位置:首页 > 产品设计 > UI/UE

有一个二叉树,现在怀疑它有一个结点有2个父节点,请写出一个函数来判断该二叉树是否存在一个节点含有2个父节点。如果存在,返回true,否则返回false。

2014-10-10 19:59 1366 查看
可以这样,要检测一个结点是否有两个父亲时,先把从该结点开始的结点与原树分离,分成两部分,然后再从原树再查找该结点,如果找到那就是有两个结点,如果没有则递归查找。</span>
struct Node{
Node *pLeft;
Node *pRight;
int Data;
};

//pTree为要查找的树,pParent为pNode的父结点,pNode为根时pParent 为NULL
//若pTree 中存在具有两个父结点的点返回真,否则返回假
bool CheckTwoParent( Node *pTree, Node *pParent, Node *pNode)
{
Node *pTemp = NULL;
bool result;
if ( pNode == NULL ) return false;
if ( pParent == NULL )  //根结点
{
if ( pTree->pLeft != NULL )
{
pTree->pLeft = NULL;
result = FindNode( pTree, pNode ); //FindNode为在pTree树中查看PNode结点存在与否,若存在返回true,否则返回false,这个很简单,可以自己写
pTree->Left = pNode;
if ( result ) return true;
}

if ( pTree->pRight != NULL )
{
pTree->pRight = NULL;
result = FindNode( pTree, pNode );
pTree->pRight = pNode;
if ( result ) return true;
}

if ( CheckTwoParent( pTree, pNode, pNode->pLeft) ) return true;
return CheckTwoParent( pTree, pNode, pNode->pRight);

}
else
{
if ( pParent->pLeft == pNode )  //若当前结点为左孩子
{
pParent->pLeft = NULL;
result = FindNode( pTree, pNode ); //FindNode为在pTree树中查看PNode结点存在与否,若存在返回true,否则返回false,这个很简单,可以自己写
pTree->Left = pNode;
if ( result ) return true;
}
else
{
pParent->pRight = NULL;
result = FindNode( pTree, pNode ); //FindNode为在pTree树中查看PNode结点存在与否,若存在返回true,否则返回false,这个很简单,可以自己写
pTree->pRight = pNode;
if ( result ) return true;
}

if ( CheckTwoParent( pTree, pNode, pNode->pLeft) ) return true;
return CheckTwoParent( pTree, pNode, pNode->pRight);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐