/*
二叉树节点定义
*/
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();
}