二叉树的嵌套括号输出(c++)

#include<iostream>
using namespace std;
typedef struct BiTNode
{
	char data;
	struct BiTNode* lchild, * rchild;
}BiTNode, * BiTree;
void CreatBitree(BiTree& T, char e)
{
	if (T == NULL)
	{
		T = new BiTNode;
		T->data = e;
		T->lchild = NULL;
		T->rchild = NULL;
	}
	else if (T->data < e)
		CreatBitree(T->rchild, e);
	else if (T->data > e)
		CreatBitree(T->lchild, e);
}
void Output(BiTree& T)
{
	if (T)
	{
		cout << T->data;
		if (T->lchild && T->rchild)
		{
			cout << "(";
			Output(T->lchild);
			cout << ",";
			Output(T->rchild);
			cout << ")";
		}
		else if (T->lchild)
		{
			cout << "(";
			Output(T->lchild);
			cout << ")";
		}
		else if (T->rchild)
		{
			cout << "(";
			Output(T->rchild);
			cout << ")";
		}
	}
}
int main()
{
	BiTree T;
	T = NULL;
	char s[200];
	cin >> s;
	for (int i = 0; i < strlen(s); i++)
	{
		CreatBitree(T, s[i]);
	}
	Output(T);
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C++二叉树的树状打印输出的代码实现: ```cpp #include <iostream> #include <vector> #include <string> using namespace std; // 二叉树节点结构体 struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; // 获取二叉树的深度 int getDepth(TreeNode* root) { if (root == NULL) { return 0; } int leftDepth = getDepth(root->left); int rightDepth = getDepth(root->right); return max(leftDepth, rightDepth) + 1; } // 中序遍历二叉树,将节点竖向的位置保存到vector容器中 void inorder(TreeNode* root, vector<string>& res, int depth, int pos) { if (root == NULL) { return; } // 遍历左子树 inorder(root->left, res, depth + 1, pos * 2); // 处理当前节点 string str(depth * 2, ' '); // 根据节点所在层数确定节点前面的空格数 str += to_string(root->val); // 将节点值转换为字符串 res[pos] = str; // 将节点字符串保存到vector容器中 // 遍历右子树 inorder(root->right, res, depth + 1, pos * 2 + 1); } // 输出二叉树 void printTree(TreeNode* root) { if (root == NULL) { return; } int depth = getDepth(root); // 获取二叉树的深度 int width = (1 << depth) - 1; // 根据二叉树的深度确定字符串长度 vector<string> res(width, string(depth * 2, ' ')); // 初始化vector容器 inorder(root, res, 0, 0); // 中序遍历二叉树,将节点竖向的位置保存到vector容器中 for (int i = 0; i < width; i++) { cout << res[i] << endl; // 输出二叉树 } } int main() { // 创建二叉树 TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->right = new TreeNode(4); root->right->left = new TreeNode(5); // 输出二叉树 printTree(root); return 0; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值