代码如下
#include<iostream>
#include<queue>
using namespace std;
class node {
public:
node(int n, bool color_type=true) :val(n), color(color_type),left(nullptr),right(nullptr),parent(nullptr) {};
int val;
node* left;
node* right;
node* parent;
bool color;
};
// ************* 输出图形二叉树 *************
void output_impl(node* n, bool left, string const& indent)
{
if (n->right)
{
output_impl(n->right, false, indent + (left ? "| " : " "));
}
cout << indent;
cout << (left ? '\\' : '/');
cout << "-----";
cout << n->val << endl;
if (n->left)
{
output_impl(n->left, true, indent + (left ? " " : "| "));
}
}
void output(node* root)
{
if (root->right)
{
output_impl(root->right, false, "");
}
cout << root->val << endl;
if (root->left)
{
output_impl(root->left, true, "");
}
}
// ***************************************
//初始化一颗二叉树,deep_max代表层数,count代表树节点数量//
void tree_init(node* root,int deep_max,int count)
{
int n = 1;
int deep_count = 0;
queue<node*> qu;
qu.push(root);
while (!qu.empty())
{
int len = qu.size();
deep_count++;
if (deep_count == deep_max)
break;
while (len--)
{
node* tree_node = qu.front();
qu.pop();
tree_node->left = new node(n++);
qu.push(tree_node->left);
if (n == count)
break;
tree_node->right = new node(n++);
qu.push(tree_node->right);
if (n == count)
break;
}
if (n == count)
break;
}
}
int main()
{
node* root = new node(0);
tree_init(root,5,100); //5层二叉树
output(root);
return 0;
}
测试结果