二叉排序树创建、中序遍历、交换左右子树输出(C++实现完整代码)
作者:互联网
二叉排序树
二叉排序树创建、中序遍历(由小到大)、交换左右子树输出(由大到小),完整C++实现代码,在Clion中编译通过。
#include "stdio.h"
#include "stdlib.h"
#include "malloc.h"
//二叉树链点定义
typedef struct bnode
{
int data;
struct bnode *lchild, *rchild;
}bnode_type;
//二叉树根的定义
typedef struct tree{
tree *root;
int num;
}tree_type;
//visit函数
void visit(bnode *t){
printf("%d ",t->data);
}
//中序遍历(递归)
void inorder(bnode_type *t)
{
if(t!=NULL){
inorder(t->lchild);
visit(t);//访问根结点
inorder(t->rchild);
}
}
void create_order_tree(bnode_type *t)//创建一个二叉有序树
{
bnode_type *p,*q;
int data1,data2;
scanf("%d",&data1);
t->data=data1;
scanf("%d",&data2);
q=t;
while(data2!=0)
{
p=(bnode_type*)malloc(sizeof(bnode_type));
p->lchild=NULL;p->rchild=NULL;
while(1)
{
if(data2<=q->data)
if(q->lchild==NULL)
{
q->lchild=p;
p->data=data2;
break;
}
else
{
q=q->lchild;
continue;
}
else
if(q->rchild==NULL)
{
q->rchild=p;
p->data=data2;
break;
}
else
{
q=q->rchild;
continue;
}
}
scanf("%d",&data2);
q=t;
}
}
//求二叉树的深度(递归)
int serch_depth(bnode *t)
{
int j=1;
int k=1;
int depth;
if(t==NULL)
return 0;
j=serch_depth(t->lchild);//递归,自己调用自己
k=serch_depth(t->rchild);
depth=(j>k?j:k)+1;
return (depth);
}
//反序函数(左子树和右子树交换顺序)
void inverted_order(bnode *t)
{
if(t==NULL){
printf("This is a empty tree\n");
return;
}
bnode *p;
p=(bnode_type*)malloc(sizeof(bnode_type));
p=t->lchild;
t->lchild=t->rchild;
t->rchild=p;
if(t->lchild!=NULL)
inverted_order(t->lchild);
if(t->rchild!=NULL)
inverted_order(t->rchild);
}
//主函数
int main(void)
{
int l;
bnode_type *p;
p=(bnode_type *)malloc(sizeof(bnode_type));
p->lchild=NULL;
p->rchild=NULL;
printf("Please input the datas and input 0 as the end\n");
create_order_tree(p);
printf("The inorder tree is:\n");
inorder(p);
printf("\n");
l=serch_depth(p);
printf("The depth of the binary tree is:\n");
printf("%d\n",l);
printf("The tree after inverted order is:\n");
inverted_order(p);
inorder(p);
}
标签:lchild,bnode,int,中序,C++,子树,rchild,NULL,type 来源: https://blog.csdn.net/tox33/article/details/88315299