程序输入一个字符串(只包含小写字母),请按照字符的输入顺序建立平衡二叉排序树,并分别输出二叉树的先序序列、中序序列和后序序列,最后输出该二叉树向左旋转 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
测试用例:
用例1:
输入:
agxnzyimk
输出:
Preorder: xigamknzy
Inorder: agikmnxyz
Postorder: agknmiyzx
Tree:
z
y
x
n
m
k
i
g
a
用例2:
输入:
asdfghjkl
输出:
Preorder: gdafjhlks
Inorder: adfghjkls
Postorder: afdhksljg
Tree:
s
l
k
j
h
g
f
d
a
代码
#include<iostream>
using namespace std;
struct AVL_Tree
{
char ch;
struct AVL_Tree *Lsons;
struct AVL_Tree *Rsons;
}*AVLnode;
void SingleRotationLeft(AVL_Tree*&T)
{
AVL_Tree*pNode;
pNode = T->Lsons;
T->Lsons = pNode->Rsons;
pNode->Rsons = T;
T = pNode;
}
void SingleRotationRight(AVL_Tree*&T)
{
AVL_Tree*pNode;
pNode = T->Rsons;
T->Rsons = pNode->Lsons;
pNode->Lsons = T;
T = pNode;
}
void DoubleRotationLR(AVL_Tree*&T)
{
AVL_Tree *t1, *t2;
t1 = T->Lsons;
t2 = t1->Rsons;
t1->Rsons = t2->Lsons;
T->Lsons = t2->Rsons;
t2->Lsons = t1;
t2->Rsons = T;
T = t2;
}
void DoubleRotationRL(AVL_Tree*&T)
{
AVL_Tree *t1, *t2;
t1 = T->Rsons;
t2 = t1->Lsons;
T->Rsons = t2->Lsons;
t1->Lsons = t2->Rsons;
t2->Lsons = T;
t2->Rsons = t1;
T = t2;
}
int Height(AVL_Tree*&T)
{
if (T == NULL)
return 0;
else
{
int HL = Height(T->Lsons);
int HR = Height(T->Rsons);
return (HL > HR ? HL + 1 : HR + 1);
}
}
void Insert(AVL_Tree*&T, char ch)
{
if (T == NULL)
{
T = new AVL_Tree();
T->ch = ch;
T->Lsons = NULL;
T->Rsons = NULL;
}
else if (ch == T->ch)
return;
else if (ch < T->ch)
{
Insert(T->Lsons, ch);
if (Height(T->Lsons) - Height(T->Rsons) == 2)
{
if (ch < T->Lsons->ch)
SingleRotationLeft(T);
else
DoubleRotationLR(T);
}
}
else
{
Insert(T->Rsons, ch);
if (Height(T->Rsons) - Height(T->Lsons) == 2)
{
if (ch > T->Rsons->ch)
SingleRotationRight(T);
else
DoubleRotationRL(T);
}
}
}
void PrintPreorder(AVL_Tree*&T)
{
if (T == NULL)
return;
else
{
printf("%c", T->ch);
PrintPreorder(T->Lsons);
PrintPreorder(T->Rsons);
}
}
void PrintInorder(AVL_Tree*&T)
{
if (T == NULL)
return;
else
{
PrintInorder(T->Lsons);
printf("%c", T->ch);
PrintInorder(T->Rsons);
}
}
void PrintPostorder(AVL_Tree*&T)
{
if (T == NULL)
return;
else
{
PrintPostorder(T->Lsons);
PrintPostorder(T->Rsons);
printf("%c", T->ch);
}
}
void PrintTree(AVL_Tree*&T, int flag)
{
if (T == NULL)
return;
else
{
PrintTree(T->Rsons, flag + 1);
for (int i = 0; i < flag; i++)
printf(" ");
printf("%c\n", T->ch);
PrintTree(T->Lsons, flag + 1);
}
}
int main()
{
char ch;
while (ch = getchar())
{
if (ch == '\n')
break;
Insert(AVLnode, ch);
}
cout<<"Preorder: ";
PrintPreorder(AVLnode);
cout << endl;
cout<<"Inorder: ";
PrintInorder(AVLnode);
cout << endl;
cout << "Postorder: ";
PrintPostorder(AVLnode);
cout << endl;
cout << "Tree:" << endl;
PrintTree(AVLnode, 0);
return 0;
}