九度OJ-1201-二叉排序树




过程:

1.定义二叉树结构与静态构造

struct Node{
    Node* rchild;
    Node* lchild;
    int value;
}tree[100];

int size;
Node* create()
{
    tree[size].rchild=tree[size].lchild=NULL;
    return &tree[size++];
}



2.三种递归遍历实现


void postorder(Node *root)
{
    if(root==NULL)
        return;
    postorder(root->lchild);
    postorder(root->rchild);
    cout<<root->value<<" ";
    
}
void inorder(Node *root)
{
    if (root==NULL)
        return;
    inorder(root->lchild);
    cout<<root->value<<" ";
    inorder(root->rchild);
}
void preorder(Node *root)
{
    if (root==NULL)
        return;
    cout<<root->value<<" ";
    preorder(root->lchild);
    preorder(root->rchild);
}


3.递归插入方法的实现


Node *insert(Node* root,int x)
{
    if (root==NULL) {
        root=create();
        root->value=x;
    }
    else if (x<root->value) {
        root->lchild=insert(root->lchild, x);
    }
    else if (x>root->value){
        root->rchild=insert(root->rchild, x);
    }
    return root;
}



4.主函数的实现

int main()
{
    int n;
    while (cin>>n) {
        size=0;
        Node* root=NULL;
        for (int i=0; i<n; i++) {
            int temp;
            cin>>temp;
            root=insert(root, temp);
        }
        preorder(root);
        cout<<endl;
        inorder(root);
        cout<<endl;
        postorder(root);
        cout<<endl;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值