您的位置:首页 > 其它

树的基本运用二

2015-06-25 10:39 323 查看
树的层次遍历:也即是从跟节点开始,每一层都从左到右输出。可利用队列的先进先出来

void Level_Traverse(Bintree root)
{
queue<Bintree>q;
Bintree temp;
temp=root;
if(temp==NULL)
return;
q.push (temp);
cout<<temp->data;
while(!q.empty ())
{
temp=q.front ();
q.pop ();
cout<<temp->data<<endl;
if(temp->lchild)
{
cout<<temp->lchild<<endl;
q.push (temp->lchild);
}
if(temp->rchild)
{
cout<<temp->rchild<<endl;
q.push (temp->rchild);
}
}
}

求树的深度:

int Depth_Bintree(Bintree *root)
{
if(!root)
return 0;
int len1,len2;
len1=Depth_Bintree(root->lchild);
len2=Depth_Bintree(root->rchild);
return (len1>len2?len1:len2)+1;
}


求树的节点个数:利用递归即可实现

int Count_Bintree(Bintree root)
{
if(root)
{
return ((Count_Bintree(root->lchild)+Count_Bintree(root->rchild))+1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: