菜鸟生成记(46)
最优二叉树
#include< iostream>
#include< vector>
using namespace std;
class Node {
public :
int w;
int l, r;
int parents;
int flag;
public :
Node ( ) {
w= 0 ;
flag= r= l= parents= - 1 ;
}
Node ( int w ) {
this - > w= w;
flag= l= r= parents= - 1 ;
}
Node ( int l, int r, int w ) {
this - > l= l;
this - > r= r;
this - > w= w;
flag= parents= - 1 ;
}
} ;
vector< Node> v;
int n;
void input ( ) ;
int findMin ( ) ;
void createTree ( ) ;
int findRoot ( ) ;
void dfs01 ( int rt) ;
void dfs02 ( int rt) ;
void dfs03 ( int rt) ;
void print ( ) ;
int main ( ) {
input ( ) ;
createTree ( ) ;
print ( ) ;
cout<< endl;
int root= findRoot ( ) ;
cout<< "根结点key:" << root<< endl;
cout<< "前序遍历哈弗曼树:" << endl;
dfs01 ( root) ;
cout<< "\n中序遍历哈弗曼树:" << endl;
dfs02 ( root) ;
cout<< "\n后序遍历哈弗曼树:" << endl;
dfs03 ( root) ;
return 0 ;
}
void input ( ) {
cout<< "输入初始结点个数:" << endl;
cin>> n;
cout<< "输入[" << n<< "]个初始结点的权值:" << endl;
for ( int i= 0 ; i< n; i++ ) {
int w;
cin>> w;
Node * node= new Node ( w) ;
v. push_back ( * node) ;
}
}
int findMin ( ) {
int minKey= - 1 ;
int minValue= 1000 ;
for ( int i= 0 ; i< v. size ( ) ; i++ ) {
if ( minValue> v[ i] . w&& v[ i] . flag== - 1 ) {
minValue= v[ i] . w;
minKey= i;
}
}
v[ minKey] . flag= 1 ;
return minKey;
}
void createTree ( ) {
int k= n;
for ( int i= n; i< 2 * n- 1 ; i++ ) {
int minKey1= findMin ( ) ;
int minKey2= findMin ( ) ;
int wSum= v[ minKey1] . w+ v[ minKey2] . w;
v[ minKey1] . parents= k;
v[ minKey2] . parents= k;
Node * newNode;
if ( v[ minKey1] . w< v[ minKey2] . w)
newNode= new Node ( minKey1, minKey2, wSum) ;
else
newNode= new Node ( minKey2, minKey1, wSum) ;
v. push_back ( * newNode) ;
k++ ;
}
}
int findRoot ( ) {
int parents= - 1 ;
for ( int i= 0 ; i< v. size ( ) ; i++ ) {
if ( v[ i] . parents== - 1 ) {
parents= i;
}
}
return parents;
}
void dfs01 ( int rt ) {
if ( rt!= - 1 ) {
cout<< v[ rt] . w<< " " ;
dfs01 ( v[ rt] . l) ;
dfs01 ( v[ rt] . r) ;
}
}
void dfs02 ( int rt ) {
if ( rt!= - 1 ) {
dfs02 ( v[ rt] . l) ;
cout<< v[ rt] . w<< " " ;
dfs02 ( v[ rt] . r) ;
}
}
void dfs03 ( int rt ) {
if ( rt!= - 1 ) {
dfs03 ( v[ rt] . l) ;
dfs03 ( v[ rt] . r) ;
cout<< v[ rt] . w<< " " ;
}
}
void print ( ) {
for ( int i= 0 ; i< n; i++ ) {
printf ( "key:%d " , i) ;
printf ( "w:%d " , v[ i] . w) ;
printf ( "left:%d right:%d " , v[ i] . l, v[ i] . r) ;
printf ( "parents:%d \n" , v[ i] . parents) ;
cout<< "-----------------" << endl;
}
for ( int i= n; i< 2 * n- 1 ; i++ ) {
printf ( "key:%d " , i) ;
printf ( "w:%d " , v[ i] . w) ;
printf ( "left:%d right:%d " , v[ i] . l, v[ i] . r) ;
printf ( "parents:%d \n" , v[ i] . parents) ;
cout<< "-----------------" << endl;
}
}
哈夫曼树构造过程
代码执行结果