3. 平衡二叉树(10分)

  1. 平衡二叉树(10分)
成绩10开启时间2019年12月1日 星期日 08:00
折扣0.8折扣时间2019年12月25日 星期三 23:55
允许迟交关闭时间2020年01月1日 星期三 23:55

程序输入一个字符串(只包含小写字母),请按照字符的输入顺序建立平衡二叉排序树,并分别输出二叉树的先序序列、中序序列和后序序列,最后输出该二叉树向左旋转 90 度后的结构。

例如:向左旋转 90 度后,以每层向里缩进 4 个空格的方式输出,输出结果为:

        i
    g
        f
a
        d
    c
        b

输入:agxnzyimk

输出:
Preorder: xigamknzy
Inorder: agikmnxyz
Postorder: agknmiyzx
Tree:

    z
        y
x
            n
        m
            k
    i
        g
            a
#include <stdio.h>
#include <stdlib.h>
struct Node
{
	char data;
	Node *left, *right;
};
Node *root = NULL;
int height(Node *p)
{
	if (p == NULL)
		return 0;
	else
	{
		if (height(p->left) > height(p->right))
			return height(p->left) + 1;
		else
			return height(p->right) + 1;
	}
}
Node *LL(Node *p)
{
	Node *q = p->left;
	p->left = q->right;
	q->right = p;
	return q;
}
Node *RR(Node *p)
{
	Node *q = p->right;
	p->right = q->left;
	q->left = p;
	return q;
}
Node *LR(Node *p)
{
	Node *q = p->left, *r = q->right;
	q->right = r->left;
	r->left = q;
	p->left = r->right;
	r->right = p;
	return r;
}
Node *RL(Node *p)
{
	Node *q = p->right, *r = q->left;
	q->left = r->right;
	r->right = q;
	p->right = r->left;
	r->left = p;
	return r;
}
Node *insert(char c, Node *p)
{
	if (p == NULL)
	{
		p = (Node *)malloc(sizeof(Node));
		p->data = c;
		p->left = p->right = NULL;
	}
	else
	{
		if (c < p->data)
		{
			p->left = insert(c, p->left);
			if (height(p->left) - height(p->right) > 1)
			{
				if (c < p->left->data)
					p = LL(p);
				else
					p = LR(p);
			}
		}
		else
		{
			p->right = insert(c, p->right);
			if (height(p->right) - height(p->left) > 1)
			{
				if (c < p->right->data)
					p = RL(p);
				else
					p = RR(p);
			}
		}
	}
	return p;
}
void preorder(Node *p)
{
	printf("%c", p->data);
	if (p->left)
		preorder(p->left);
	if (p->right)
		preorder(p->right);
}
void inorder(Node *p)
{
	if (p->left)
		inorder(p->left);
	printf("%c", p->data);
	if (p->right)
		inorder(p->right);
}
void postorder(Node *p)
{
	if (p->left)
		postorder(p->left);
	if (p->right)
		postorder(p->right);
	printf("%c", p->data);
}
void print(Node *p, int depth)
{
	int i;
	if (p->right)
		print(p->right, depth + 1);
	for (i = 0; i < depth; i++)
		printf("    ");
	printf("%c\n", p->data);
	if (p->left)
		print(p->left, depth + 1);
}
int main()
{
	char c;
	while (1)
	{
		c = getchar();
		if (c == '\n')
			break;
		root = insert(c, root);
	}
	printf("Preorder: ");
	preorder(root);
	printf("\nInorder: ");
	inorder(root);
	printf("\nPostorder: ");
	postorder(root);
	printf("\nTree:\n");
	print(root, 0);
	return 0;
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值