二叉搜索树2

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    node *lchild,*rchild;
};
void insertt(node *&tree,int value)//注意要加&(取地址符)才能每次更新tree 否则不能实现对tree的改变(相当           
                                   //于swap交换两个值,不加取地址只能相当于一个函数,里边的tree不会
                                   //时时改变)
{
    node *t=new node();

    t->data=value;
    t->lchild=NULL;
    t->rchild=NULL;
    if(tree==NULL)
    {
       tree=t;
    }
    else
    {
        node *temp=new node();
        temp = tree;
        while(temp!=NULL)
        {
            if(value<temp->data)
            {
                if(temp->lchild==NULL)
                {
                    temp->lchild=t;

                    break;
                }
                else
                {
                    temp=temp->lchild;
                }
            }
            else
            {
                if(temp->rchild==NULL)
                {
                    temp->rchild=t;

                    break;
                }
                else
                    temp=temp->rchild;
            }
        }
    }
}
void preorder(node *t)
{
    if(t)
    {
        cout<<t->data<<endl;
        preorder(t->lchild);
        preorder(t->rchild);
    }
}

void inorder(node*t)
{
    if(t)
    {
        inorder(t->lchild);
        cout<<t->data<<endl;
        inorder(t->rchild);
    }
}

void postorder(node*t)
{
    if(t)
    {
        postorder(t->lchild);
        postorder(t->rchild);
        cout<<t->data<<endl;
    }
}
int main()
{
    int arr[8]= {6,3,8,2,5,1,7};
    node *tree=new node();
    tree=NULL;
    for(int i=0;i<7;i++)
    {
        insertt(tree,arr[i]);
    }
    cout<<tree->data<<endl;
    postorder(tree);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值