泛型编程 二叉树与数组的相互转换,打印,获取二叉树深度

/*
		二叉树节点定义
	*/
	template<typename T=void>
	struct Binary_Tree {
		T* val;
		Binary_Tree* left;
		Binary_Tree* right;
		Binary_Tree(T _val) :left(nullptr),right(nullptr){
			val = new T(_val);
		}
		~Binary_Tree() {
			if(val)delete val;
		}
	};
	/*
		获取二叉树的深度
	*/
	template<typename T = void>
	static void get_binary_tree_depth(const Binary_Tree<T>* root, uint32_t& max_depth, uint32_t depth=0)
	{
		depth++;
		if (root)
		{
			max_depth = depth > max_depth ? depth : max_depth;
			get_binary_tree_depth(root->left, max_depth, depth );
			get_binary_tree_depth(root->right, max_depth, depth );
		}
	}
	/*
		从数组构建二叉树
	*/
	template<typename T = void>
	static void build_binary_tree_from_vector(std::vector<T*>&input, int64_t read_pos, Binary_Tree<T>** root)
	{
		if (read_pos<input.size()&&input[read_pos]!=nullptr)
		{
			*root = new Binary_Tree<T>(*input[read_pos]);
			build_binary_tree_from_vector(input, 2*read_pos + 1, &(*root)->left);
			build_binary_tree_from_vector(input, 2*read_pos + 2, &(*root)->right);
		}
	}
	/*
		从二叉树转成数组
	*/
	template<typename T = void>
	static void covert_binary_tree_to_vector(std::vector<T*>& empty_vector, int64_t write_pos,  Binary_Tree<T>* root)
	{
		if (root)
		{
			if(empty_vector.size()<= write_pos)empty_vector.resize(write_pos + 1);
			empty_vector[write_pos] = new T(*(root->val));
			covert_binary_tree_to_vector(empty_vector, 2 * write_pos + 2, root->right);
			covert_binary_tree_to_vector(empty_vector, 2 * write_pos + 1, root->left);
		}
	}
	/*
		打印二叉树
	*/
	template<typename T = void>
	static void print_binary_tree( Binary_Tree<T>* root,int val_width=-1)
	{
		uint32_t max_depth = 0;
		val_width = val_width > 0 ? val_width : sizeof(val_width) * 2+1;
		get_binary_tree_depth(root, max_depth);
		std::vector<T*>empty_vector;
		covert_binary_tree_to_vector<T>(empty_vector, 0, root);
		uint32_t total_elements = 0;
		std::cout.fill(' ');
		std::cout.setf(std::ios::left);
		for (uint32_t i = 0; i < max_depth; i++)
		{
			uint32_t element_nums = std::pow(2, i);
			for (uint32_t j = 0; j < element_nums && j + total_elements < empty_vector.size(); j++) {
				uint32_t fills = 0;
					fills = j == 0? (std::pow(2, max_depth - 1 - i) - 1)*val_width: (std::pow(2, max_depth - i) - 1) * val_width;
				if (fills > 0) {
					std::string fill_string(fills, '\0');
					std::cout << fill_string;
				}
				if (empty_vector[total_elements + j] != nullptr)std::cout << *empty_vector[total_elements + j];
				else std::cout << " ";
			}
			std::cout << "\r\n";
			std::cout.unsetf(std::ios::left);
			total_elements += element_nums;
			if (total_elements >= empty_vector.size())break;
		}
		for (auto i : empty_vector)delete i;
		empty_vector.clear();
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值