二叉树宽度

代码如下:

//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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值