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

[cpp]  view plain  copy
  1. struct Node{  
  2. Node *pLeft;  
  3. Node *pRight;  
  4. int Data;  
  5. };  
  6.   
  7. //pTree为要查找的树,pParent为pNode的父结点,pNode为根时pParent 为NULL  
  8. //若pTree 中存在具有两个父结点的点返回真,否则返回假  
  9. bool CheckTwoParent( Node *pTree, Node *pParent, Node *pNode)  
  10. {  
  11.     Node *pTemp = NULL;  
  12.     bool result;  
  13.     if ( pNode == NULL ) return false;  
  14.     if ( pParent == NULL )  //根结点  
  15.     {  
  16.         if ( pTree->pLeft != NULL )  
  17.         {  
  18.            pTree->pLeft = NULL;  
  19.            result = FindNode( pTree, pNode ); //FindNode为在pTree树中查看PNode结点存在与否,若存在返回true,否则返回false,这个很简单,可以自己写  
  20.            pTree->Left = pNode;  
  21.            if ( result ) return true;  
  22.         }  
  23.   
  24.         if ( pTree->pRight != NULL )  
  25.         {  
  26.             pTree->pRight = NULL;  
  27.             result = FindNode( pTree, pNode );  
  28.             pTree->pRight = pNode;  
  29.             if ( result ) return true;  
  30.         }  
  31.   
  32.        if ( CheckTwoParent( pTree, pNode, pNode->pLeft) ) return true;  
  33.        return CheckTwoParent( pTree, pNode, pNode->pRight);  
  34.   
  35.     }  
  36.     else  
  37.     {  
  38.         if ( pParent->pLeft == pNode )  //若当前结点为左孩子  
  39.         {  
  40.             pParent->pLeft = NULL;  
  41.             result = FindNode( pTree, pNode ); //FindNode为在pTree树中查看PNode结点存在与否,若存在返回true,否则返回false,这个很简单,可以自己写  
  42.             pTree->Left = pNode;  
  43.             if ( result ) return true;  
  44.         }  
  45.         else  
  46.         {  
  47.             pParent->pRight = NULL;  
  48.             result = FindNode( pTree, pNode ); //FindNode为在pTree树中查看PNode结点存在与否,若存在返回true,否则返回false,这个很简单,可以自己写  
  49.             pTree->pRight = pNode;  
  50.             if ( result ) return true;  
  51.         }  
  52.   
  53.        if ( CheckTwoParent( pTree, pNode, pNode->pLeft) ) return true;  
  54.        return CheckTwoParent( pTree, pNode, pNode->pRight);  
  55.     }  
  56.   
  57. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值