二叉排序树创建、中序遍历、交换左右子树输出(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);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值