#include<iostream>
using namespace std;
int a, b, c = 0; //a代表叶子结点,b代表度为1的结点,c代表度为2点结点
typedef struct BiTNode
{
char data;
struct BiTNode* rchild, * lchild;
}BiTNode, * BiTree;
void CreatBiTree(BiTree& T, char s[], int& i)
{
if (s[i] == '0')
T = NULL;
else
{
T = new BiTNode;
T->data = s[i];
CreatBiTree(T->lchild, s, ++i);
CreatBiTree(T->rchild, s, ++i);
}
}
int Depth(BiTree T) //求高度
{
if (!T)
return 0;
else if (!T->lchild && !T->rchild)
return 1;
return Depth(T->lchild) >= Depth(T->rchild) ? Depth(T->lchild) + 1 : Depth(T->rchild) + 1;
}
void count(BiTree T) //统计结点个数
{
if (T)
{
if (T->lchild && T->rchild)
c++;
else if (T->lchild || T->rchild)
b++;
else
a++;
count(T->lchild);
count(T->rchild);
}
}
void Change(BiTree& T) //左右孩子交换
{
if (T && T->lchild || T->rchild)
{
BiTree p = new BiTNode;
p = T->lchild;
T->lchild = T->rchild;
T->rchild = p;
Change(T->lchild);
Change(T->rchild);
}
}
void PreOrder(BiTree T) //先序遍历
{
if (T)
{
cout << T->data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
int main()
{
char s[100];
BiTree T;
while (cin >> s && s[0] != '0')
{
int i = -1;
CreatBiTree(T, s, ++i);
cout << "高度为:";
cout << Depth(T) << endl;
count(T);
cout << "各结点个数为:";
cout << a << " " << b << " " << c;
cout << endl;
Change(T);
cout << "交换结点后先序序列为:";
PreOrder(T);
}
return 0;
}
二叉树高度、结点数统计、左右孩zi交换(c++)
于 2022-03-22 18:13:43 首次发布