#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#define maxn 1000
#define T char
using namespace std;
typedef struct btnode {
T data;
struct btnode *lchild;
struct btnode *rchild;
}btnode;
btnode *root = NULL;
btnode *temp2 = NULL;
int leaf_number = 0;
btnode* newnode(T x) {
btnode* p = (btnode* )malloc(sizeof(btnode));
p->data = x;
p->lchild = NULL;
p->rchild = NULL;
return p;
}
bool insert1(T x) { //插入节点
btnode *r = NULL, *q = NULL, *p = root;
T k = x;
while(p) {
q = p;
if(k < p->data) {
p = p->lchild;
}
else if(k > p->data) {
p = p->rchild;
}
else {
cout << "duplicate!" << endl;
return false;
}
}
r = newnode(x);
if(root) {
if(k < q->data) {
q->lchild = r;
}
else {
q->rchild = r;
}
}
else{
root = r;
}
return true;
}
void exchange(btnode *bt) { //交换左右子树。
if(bt) {
exchange(bt->lchild);
exchange(bt->rchild);
}
if(bt == NULL) {
return ;
}
temp2 = bt->lchild;
bt->lchild = bt->rchild;
bt->rchild = temp2;
}
void midorder(btnode *bt) {
if(bt) {
midorder(bt->lchild);
cout << bt->data << ' ';
midorder(bt->rchild);
}
if(bt == NULL) {
return ;
}
}
int total(btnode *bt) { //求节点总数。感觉写的太缀余。
int rnum = 0, lnum = 0;
int num = 0;
if(!bt) {
return 0;
}
if(bt->lchild == NULL && bt->rchild == NULL) {
leaf_number++;
return 1;
}
if(bt->lchild == NULL && bt->rchild != NULL) {
return rnum = total(bt->rchild) + 1;
}
if(bt->lchild != NULL && bt->rchild == NULL) {
return lnum = total(bt->lchild) + 1;
}
if(bt->lchild != NULL && bt->rchild != NULL) {
lnum = total(bt->lchild);
rnum = total(bt->rchild);
return num = lnum + rnum + 1;
}
return 0;//suseless
}
int height(btnode *t) { //求树的高度。
int lh = 0, rh = 0;
if(!t) {
return 0;
}
else{
lh = height(t->lchild);
rh = height(t->rchild);
if(lh>rh){
return lh+1;
}
else{
return rh+1;
}
}
}
void preorder(btnode *bt) {
if(bt == NULL) {
return ;
}
if(bt) {
cout << bt->data << ' ';
preorder(bt->lchild);
preorder(bt->rchild);
}
}
int main()
{
char str[maxn];
int len = 0;
gets(str);
len = strlen(str);
for(int i = 0; i < len; i++) {
insert1(str[i]);
}
btnode *temp = root;
cout << "preorder: ";
preorder(temp);
cout << endl;
cout << "midorder: ";
midorder(temp);
cout << endl;
exchange(temp);
cout << "preorder: ";
preorder(temp); cout << endl;
cout << "midorder: ";
midorder(temp); cout << endl;
int Total = total(temp);
printf("The amount of the node: ");
cout << Total << endl;
printf("The height of the tree: ");
int heigh = height(temp);
cout << heigh << endl;
printf("The leaf of the tree: ");
cout << leaf_number << endl;
return 0;
}
/******************************************************************
最近忙着备考,几乎很少写程序,完美结束考试,全心学习编程。
程序仅仅说明道理,如果想完善稍加改动即可!
测试数据:5382469170
********************************************************************/
二叉搜索树
最新推荐文章于 2025-04-29 16:04:18 发布