对树的几个基本操作函数


//显示树中所有节点的值
void show(tnode<int> *root)
{
 if (root)
 {
  cout<< root->value<<"/n";
  show(root->left);
  show(root->right);
 }
}

//输入树的每层节点值
void GetLayer(tnode<int>*root,vector<int>& v)
{
 if (root == NULL)
  return ;

 queue< tnode<int>* > q;
 tnode<int> *p;
 q.push(root);

 while( !q.empty())
 {
  p = q.front();
  v.push_back(p->value);
  q.pop();

  if (p->left != NULL)
   q.push(p->left);
  if (p->right != NULL)
   q.push(p->right);
 }
}

//计算树的叶节点个数
void CountLeaf(tnode<int>*root, int &nCount)
{
 if ( NULL == root)
  return;

 if ( (NULL ==root->left ) && (NULL == root->right) )
    ++nCount;
    CountLeaf(root->left, nCount);
 CountLeaf(root->right,nCount);
}

//计算树深度
int CoutDepth(tnode<int>*root)
{
 int depthLeft = 0, depthRight = 0, depthVal = 0;

 if ( NULL == root)
  depthVal = - 1;
 else
 {
  depthLeft = CoutDepth(root->left);
  depthRight= CoutDepth(root->right);

  depthVal = 1 + (depthLeft > depthRight ? depthLeft : depthRight);
 }

 return depthVal;
}

//树节点的个数
void nodeCout(tnode<int>*root, int &n)
{
 if (NULL == root)
  return;
 if (root)
 {
  ++n;
  nodeCout(root->left,n);
  nodeCout(root->right,n);
 }
}

//复制树
tnode<int>* Copy(tnode<int>*root)
{
 tnode<int>*left, *right, *newNode;

 if (NULL == root)
  return NULL;

 left = Copy(root->left);
    right = Copy(root->right);

 newNode = new tnode<int>(root->value,left,right);

 return newNode;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值