C++ 图形化 打印二叉树

代码如下

#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;
}

测试结果
在这里插入图片描述

  • 3
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值