实验四:树和二叉树的实验

#include<iostream.h>
#define MaxLength 10    
class BiTree
{
 int node[MaxLength]; 
    int length; 
public:
 BiTree(int *bTree,int n); 
 ~BiTree(){}        
 void Leveroder();     
 void OutPut(int length); 
 void Leaf();
};
BiTree::BiTree(int *bTree,int n)
{
 if(n>=MaxLength||n<1)throw"数组已满!||已空!";
 for(int i=0;i<n;i++)
 {
  if(bTree[i]==0) 
   node[i]=NULL;
  else node[i]=bTree[i];
 }
 length=n;
}
void BiTree::Leveroder()  现 
{   
    for(int i=0;i<length;i++)   
    {   
        if(node[i]!=NULL)  
            cout<<node[i]<<"  ";  
    }   

void BiTree::OutPut(int length)
{
  for(int j=1;j<length;j++)
 {
   if(node[j]==NULL)
   {
    cout<<"第"<<j<<"个结点不存在!"<<endl;
    continue;
   }
  else cout<<"第"<<j<<"个结点值:"<<node[j]<<"\t";
  if(node[j/2]==NULL) 
   cout<<"无双亲!"<<"\t";
  else cout<<"双亲:"<<node[j/2]<<"\t";
  if(node[2*j]==NULL||(2*j)>=length) 
   cout<<"无左孩子!"<<"\t";
  else cout<<"左孩子:"<<node[2*j]<<"\t";
  if(node[2*j+1]==NULL||(2*j+1)>=length)
   cout<<"无右孩子!"<<endl;
  else cout<<"右孩子:"<<node[2*j+1]<<endl;
 }
}
void BiTree::Leaf()
{   
    int node1,node2;   
    for(int i=1;i<=length;i++)   
    {   
        node1=2*i;   
        node2=2*i+1;    
        if(node[node1]==NULL&&node[node2]==NULL&&node[i]!=NULL)
            cout<<node[i-1]<<"  ";   
        if(node1>length&&node[i-1]!=NULL)  
            cout<<node[i-1]<<"  ";   
    }   
}   
int main()
{
 int bTree[6]={8,6,1,36,26,40}; 
 BiTree node(bTree,6);
 cout<<"层序输出结点数据为:"<<endl;
 node.Leveroder();
 cout<<endl;
 node.OutPut(6);
 cout<<endl;
 cout<<"叶子结点:"<<endl;
 node.Leaf();
 cout<<endl;
 return 0;
}
展开阅读全文

没有更多推荐了,返回首页