二叉树
#include <iostream>
using namespace std;
typedef struct binode{
char data;//数据
struct binode*lchild,*rchild;//左孩子右孩子
}binode,*tree;
void pre(tree T){//前序遍历
if(!T)return;//如果不存在停止
else{
cout<<T->data<<endl;
pre(T->lchild);
pre(T->rchild);
}
}
void in(tree T){//中序遍历
if(!T)return;
else{
pre(T->lchild);
cout<<T->data<<endl;//函数执行完在打印
pre(T->rchild);
}
}
void post(tree T){//后序遍历
if(!T)return;
else{
pre(T->lchild);
pre(T->rchild);
cout<<T->data<<endl;
}
}
int create(tree&T){//前序遍历创造二叉树
char a;
cout<<"请输入数据:"<<endl;
cin>>a;
if(a=='#')T=NULL;//节点为空
else{
T=new binode;
T->data=a;
create(T->lchild);
create(T->rchild);
}
return 1;
}
int depth(tree T){//树的深度
if(!T)return 0;
else{
int m=depth(T->lchild);
int n=depth(T->rchild);
if(m>=n)return m+1;
else return n+1;
}
}
int nodecount(tree T){
if (T == NULL) return 0;
else return nodecount(T->lchild) + nodecount(T->rchild)+1;
}
int leafcount(tree T){
if (T == NULL) return 0;
if (T->lchild == NULL && T->rchild == NULL) return 1;
else return leafcount(T->lchild) + leafcount(T->rchild);
}
int main(){
tree T;
create(T);
pre(T);
cout<<depth(T)<<endl
<<nodecount(T)<<endl
<<leafcount(T);
return 0;
}
哈夫曼树
#include<iostream>
#include <vector>
using namespace std;
typedef struct node
{
int weight; //权重
int parent, lchild, rchild; //每个结点的双亲、左右孩子的数组下标
} *htree;
void select(htree&h,int n,int&i1,int&i2);
void init(htree&h,int n){
h=new node[2*n];
for (int i = 1; i < 2 * n; ++i)
{
h[i].parent = h[i].lchild = h[i].rchild = 0;//右结合律
}
int input;
for (int i = 1; i <= n; ++i)
{cout<<"请输入权值:"<<endl;
cin >> input;
h[i].weight = input;
}
}
void create(htree&h,int length){
init(h,length);
for (int i = length + 1; i < 2 * length; ++i)
{
int i1 = 0, i2 = 0;
select(h, i - 1, i1,i2);//重点是这个Select算法
h[i].weight = h[i1].weight + h[i2].weight;//
h[i1].parent = h[i2].parent = i;
h[i].lchild = i1;
h[i].rchild = i2;
}
}
void select(htree&h,int n,int&i1,int&i2)
{
vector<int> vec;
for (int i = 1; i <= n; ++i)
{
if (h[i].parent == 0)
{
vec.push_back(i);
}
}
//找出最小的一个
auto flag1 = vec.begin();
for (auto it = vec.begin() + 1; it != vec.end(); ++it)
{
if (h[*it].weight < h[*flag1].weight)
{
flag1 = it;
}
}
i1 = *flag1; //最小的元素下标
vec.erase(flag1);
auto flag2 = vec.begin();
for (auto it = vec.begin() + 1; it != vec.end(); ++it)
{
if (h[*it].weight < h[*flag2].weight)
{
flag2 = it;
}
}
i2 = *flag2; //第二小的元素的下标
}
int main(){
return 0;
}