二叉树的其他操作

来源:互联网 发布:windows7安装apache 编辑:程序博客网 时间:2024/06/05 16:28

二叉树的操作

  • 树中节点的数目
    int Size(bt_node *ptr)  // 树中所有节点的数目{  if(ptr == NULL)       return 0;  else      return 1+Size(ptr->leftchild)+Size(ptr->rightchild);}int SizeLeaf(bt_node *ptr)  // 树中叶子节点的数目{  if(ptr == NULL)      return 0;  else if(ptr->leftchild == NULL && ptr->rightchild == NULL)  {      return 1;  }else   {      return SizeLeaf(ptr->leftchild)+SizeLeaf(ptr->rightchild);  }}int SizeOneBranch(bt_node *ptr)  // 树中单分支节点的数目{  if(ptr == NULL)      return 0;  else if((ptr->leftchild != NULL && ptr->rightchild == NULL)||ptr->leftchild == NULL && ptr->rightchild != NULL))  {      return 1;  }else   {      return SizeLeaf(ptr->leftchild)+SizeLeaf(ptr->rightchild);  }}int SizeTwoBranch(bt_node *ptr)  // 树中双分支节点的数目{  if(ptr == NULL)      return 0;  else if(ptr->leftchild != NULL && ptr->rightchild != NULL)  {      return 1;  }else   {      return SizeLeaf(ptr->leftchild)+SizeLeaf(ptr->rightchild);  }}
  • 树的深度
    int Max(int a,int b){  return a>b? a:b;}int Depth(bt_node *ptr){  if(ptr == NULL)  {      return 0;  }else  {      return Max(Depth(ptr->leftchild),Depth(ptr->rightchild)) + 1;  }}
  • 寻找父亲节点
    bt_node * Parent(bt_node *ptr,bt_node *child){  if(ptr == NULL || ptr->leftchild == child || ptr->rightchild == child)  {      return ptr;  }else  {      bt_node *p = Parent(ptr->leftchild,child);      if(NULL == p)      {          p = Parent(ptr->rightchild,child);      }      return p;  }}bt_node * FindParet(bt_node *ptr,bt_node *child){  if(ptr == NULL || child == NULL || ptr == child)  {      return NULL;  }else  {      return Parent(ptr,child);  }}
原创粉丝点击