树的基本运用二

来源:互联网 发布:怎么购买已备案域名 编辑:程序博客网 时间:2024/05/05 08:56

树的层次遍历:也即是从跟节点开始,每一层都从左到右输出。可利用队列的先进先出来

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);}}



 

0 0
原创粉丝点击