- 平衡二叉树(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;
}