代码如下:
//node.h
struct node{
int value;
node *lchild;
node *rchild;
};
//tree.h
#include "node.h"
#include <fstream.h>
class tree{
public:
tree();
node* pre_build_tree(char *filename);
int wight();
private:
int prv_wight(node *root);
void prv_level_num(node *root, int *a, int hight);
int prv_size(const node* root);
int array_max(int *a, int n);void init_array(int *a, int n);
private:node *root;
};
void tree::prv_pre_build_tree(node *&root, ifstream &fs){
if(!fs.eof()){
int temp;
fs >> temp;
if(temp != -1){
root = new node;
root -> value = temp;
root -> lchild = root -> rchild = NULL;
prv_pre_build_tree(root -> lchild, fs);
prv_pre_build_tree(root -> rchild, fs);
}
}
}
node* tree::pre_build_tree(char *filename){
ifstream fs;
fs.open(filename, ios::in);
prv_pre_build_tree(root, fs);
fs.close();
cout << root << endl;
return root;
}
//tree.cpp
int tree::prv_wight(node *root){ int node_num = hight(); int *level_num = new int[node_num]; init_array(level_num, node_num); prv_level_num(root, level_num, 0); return array_max(level_num, node_num); } void tree::init_array(int *a, int n){ for( int i = 0; i < n; ++ i){ a[i] = 0; } } int tree::array_max(int *a, int n){ int max = a[0]; for(int index = 1; index < n; ++ index){ if(a[index] >= max){ a[index] = a[index] + max; max = a[index] - max; a[index] = a[index] - max; } } return max; } int tree::wight(){ return prv_wight(root); } void tree::prv_level_num(node *root, int *a, int hight){ /* a数组用来存放每层的结点个数,分治的思想是对于任意一棵子二叉树,根层 结点数是1,第一层的结点个数是左边结点个数加上右边结点个数。 */ if(root == NULL){ hight = 0; }else{ a[hight] += 1; prv_level_num(root -> lchild, a, hight + 1); prv_level_num(root -> rchild, a, hight + 1); } } int tree::size(){ return prv_size(root); } int tree::prv_size(const node *root){ if(root == NULL){ return 0; }else{ return 1 + prv_size(root -> lchild) + prv_size(root -> rchild); } }