树
- 结点的度:某节点所拥有的子树的个数
- 层数:根节点的层数为一,以此类推
- 深度:树中所有结点的最大深度,也叫树的高度
- 宽度:树的每一层结点个数的最大值称为树的宽度
二叉链表实现二叉树:
struct Node{
char data;
Node *l,*r;
};
class Bitree{
private:
Node *root;//指向根节点的头指针
Node *Creat();
void Release(Node *bt);
void PreOrder(Node *bt);
void InOrder(Node *bt);
void PostOrder(Node *bt);
void Order(Node *bt);
int High(Node *bt);
void Exchange(Node *bt);
public:
Bitree(){root=Creat();}
~Bitree(){Release(root);}
void PreOrder(){PreOrder(root);}//前序
void InOrder(){InOrder(root);}//中序
void PostOrder(){PostOrder(root);}//后序
void Order(){Order(root);}//计算叶子节点个数
void High(){cout<<High(root)<<endl;}//计算树的高度
void Exchange(){Exchange(root);}//交换左右子树
};
前序遍历:
void Bitree::PreOrder(Node *bt)
{
if(bt==NULL)
return;
cout<<bt->data;
PreOrder(bt->l);
PreOrder(bt->r);
}
中序遍历:
void Bitree::InOrder(Node *bt)
{
if(bt==NULL)
return;
InOrder(bt->l);
cout<<bt->data;
InOrder(bt->r);
}
后序遍历:
void Bitree::PostOrder(Node *bt)
{
if(bt==NULL)
return;
PostOrder(bt->l);
PostOrder(bt->r);
cout<<bt->data;
}
构造:(根据结点序列来构造二叉树)
Node* Bitree::Creat()
{
Node *bt;
char ch;
cin>>ch;
if(ch=='#')bt=NULL;
else
{
bt=new Node;
bt->data=ch;
num1++;//全局变量,构造过程中计算结点个数
bt->l=Creat();
bt->r=Creat();
}
return bt;
}
析构:
void Bitree::Release(Node *bt)
{
if(bt==NULL)
return;
Release(bt->l);
Release(bt->r);
delete bt;
}
计算叶子节点个数:
void Bitree::Order(Node *bt)
{
if(bt)
{
if(bt->l==NULL&&bt->r==NULL)
{
num2++;//全局变量,计算叶子节点个数
}
else
{
Order(bt->l);
Order(bt->r);
}
}
return;
}
计算树的高度:
int Bitree::High(Node *bt)
{
int high1=0,high2=0;
if(bt==NULL) return 0;
high1=High(bt->l);
high2=High(bt->r);
if(high1>high2) return high1+1;
else return high2+1;
}
交换左右子树:
void Bitree::Exchange(Node *bt)
{
if(bt)
{
Node *temp;
temp=bt->l;
bt->l=bt->r;
bt->r=temp;
Exchange(bt->l);
Exchange(bt->r);
}
else return;
}