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

2018-10-11  本文已影响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; 
}
上一篇下一篇

猜你喜欢

热点阅读