美文网首页
求树的深度&判断两棵树是否相同

求树的深度&判断两棵树是否相同

作者: 小码弟 | 来源:发表于2018-10-11 09:34 被阅读0次
    th.jpg

    求二叉树的深度(递归)

    int Depth(BTree root)
    {
      int ldepth, rdepth;
      if(root)
      {
        ldepth = Depth(root->lchild);
        rdepth = Depth(root->rchild);
        return (ldepth>rdepth?ldepth:rdepth)+1;
      }
      else
        return 0;
    }
    

    判断两棵树是否相同

    void IsSame(BTree t1, BTree t2)
    {
      if(t1==NULL && t2 == NULL)
      return true;
    
      if(t1==NULL && t2)
      return false;
    
      if(t1 && t2 == NULL)
      return false;
      
      if(t1->data == t2->data)
      return IsSame(t1->lchild, t2->lchild)&&IsSame(t1->rchild, t2->rchild);
      else
        return false; 
    }
    

    相关文章

      网友评论

          本文标题:求树的深度&判断两棵树是否相同

          本文链接:https://www.haomeiwen.com/subject/gtbvaftx.html