/*
哈夫曼树
最优二叉树 严格二叉树 正则二叉树
*/
#include <iostream>
#include <stack>
using namespace std;
typedef struct node{
int value ;
struct node *left,*right,*father;
}HFM;
void Sort(int *arr,int length) /*节点排序*/
{
if (arr == NULL || length <= 0) return ;
int flag ;
for(int i=0;i<length;i++){
flag = 0;
for(int j=0;j<length-i-1;j++){
if(arr[j] < arr[j+1]){
arr[j] = arr[j]^arr[j+1];
arr[j+1] = arr[j+1]^arr[j];
arr[j] = arr[j]^arr[j+1];
flag = j+1;
}
}
if(flag == 0) break;
i = length - flag - 1;
}
}
void CreateHFM(HFM** &root,int *arr,int length) /*创建哈夫曼树*/
{
Sort(arr,length);
int k=length-1;
root = new HFM*[2*length-1];
HFM* node = NULL;
for(int i = 2*length-2;i>=0;i-- ){
node = new HFM;
node->value = arr[k]; node->left = NULL; node->right = NULL; node->father = NULL;
if( k == length-1 || k == length-2){
root[i] = node;
k--;
}
else{
if( i%2 == 0 ){
node->value = root[i+1]->value + root[i+2]->value;
if(i == 0){
node->father = NULL;
}
root[i] = node;
if(i == 2*length - 4){
root[i]->left = root[i+2]; root[i]->right = root[i+1];
}
else{
root[i]->left = root[i+1]; root[i]->right = root[i+2];
}
root[i+1]->father = root[i]; root[i+2]->father = root[i];
}
else{
root[i] = node;
k--;
}
}
}
}
void Traver_x(HFM* root) /*递归先序遍历*/
{
if (root == NULL) return ;
cout<<root->value <<" ";
Traver_x(root->left);
Traver_x(root->right);
}
void Traver_z(HFM* root) /*递归中序遍历*/
{
if (root == NULL) return ;
Traver_z(root->left);
cout<<root->value <<" ";
Traver_z(root->right);
}
void Traver_h(HFM* root) /*递归后续遍历*/
{
if (root == NULL) return ;
Traver_h(root->left);
Traver_h(root->right);
cout<<root->value <<" ";
}
void f_Traver_h(HFM* root) /*非递归后序遍历*/
{
if(root == NULL) return ;
HFM* tmp = NULL;
int tag;
stack<HFM*> stack_hfm;
do{
/*左子树入栈*/
while(root){
stack_hfm.push(root);
root = root->left;
}
tag =1; tmp = NULL;
while(!stack_hfm.empty() && tag){
root = stack_hfm.top();
if(root->right == tmp){
cout<<root->value<<" ";
tmp = root;
stack_hfm.pop();
}
else{
root = root->right;
tag =0;
}
}
}while(!stack_hfm.empty());
cout<<endl;
}
int main()
{
HFM** hfm = NULL;
int arr[] = {4,2,3,1};
CreateHFM(hfm,arr,sizeof(arr)/sizeof(int));
Traver_x(*hfm);
cout<<endl;
Traver_z(*hfm);
cout<<endl;
Traver_h(*hfm);
cout<<endl;
f_Traver_h(*hfm);
system("pause");
return 0;
}