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

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

2017-09-10 00:12 1166 查看
[cpp] view
plain copy

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);  

    }  

  

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