数组递归建树与指针递归建树&&二叉搜索树的构造

给点前序序列
abc##de#g##f### #表示空树
数组前序递归建树

#include<stdio.h>
#include<stdlib.h>
const int N1=1e8+5;
const int N2=1e2+5;
int pos,len,t;
char tree[N1];
char str[N2];
void create(int pos)//建立二叉树
{
    char c = str[t++];
    if(c == '#')//若是‘#’,说明该节点为空返回上一级节点
        return;
    tree[pos] = c;//若不是‘#’,为本节点赋值
    create(pos*2);//递归创建左子树
    create(pos*2+1);//递归创建右子树
}
void traverse(int root)//中序遍历二叉树
{
    if(tree[root]==0)//如果该节点为0,说明该节点为空,返回上一级
        return;
    traverse(2*root);//先遍历左子树
    printf("%c ",tree[root]);//遍历完左子树后,访问本节点
    traverse(2*root+1);//再遍历右子树
}
int main()
{
    while(scanf("%s",str)!=EOF)
    {
        t=0;
        create(1);
        traverse(1);
        printf("\n");
    }
}

指针递归建树

#include<bits/stdc++.h>
using namespace std;
string s;
int pos=0;
typedef struct tree_node
{
    char val;
    struct tree_node * l;
    struct tree_node *r;
    tree_node(char c):val(c),l(NULL),r(NULL){};
} tree_node;
tree_node *build()
{
    char c=s[pos++];
    if(c=='#')
    {
        return NULL;
    }
  tree_node * root=new tree_node(c);
    root->l=build();
    root->r=build();
    return root;
}
void mid(tree_node *root)
{
    if(root!=NULL)
    {
        mid(root->l);
        cout<<root->val<<" ";
        mid(root->r);
    }
    return ;
}
int main()
{
    cin>>s;
    tree_node* root=build();
    mid(root);
    return 0;
}

二叉搜索树

#include<bits/stdc++.h>
using namespace std;
typedef struct node{
    int val;
    int l;
    int r;
}node;
node v[1000004];
int num;
void build(int root,int val)
{
    if(v[root].val==0)
    {
        v[root].val=val;
        return ;
    }
    if(v[root].val==val)
    {
        return;
    }
    if(val<v[root].val)
    {
        if(v[root].l==0)
        {
            v[root].l=++num;
        }
        build(v[root].l,val);
    }
    else
    {
        if(v[root].r==0)
        {
            v[root].r=++num;
        }
        build(v[root].r,val);
    }
    return ;
}
void pre(int root)
{
    if(v[root].val!=0)
    {
        cout<<v[root].val<<" ";
        pre(v[root].l);
        pre(v[root].r);
    }
    return ;
}
void mid(int root)
{
    if(v[root].val!=0)
    {
        mid(v[root].l);
        cout<<v[root].val<<" ";
        mid(v[root].r);
    }
    return ;
}
void hou(int root)
{
    if(v[root].val!=0)
    {
        hou(v[root].l);
        hou(v[root].r);
        cout<<v[root].val<<" ";
    }
    return ;
}
int a[1000005];
int main()
{
    int n;
    num=1;
    cin>>n;
    v[1].val=a[1];
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        build(1,a[i]);
    }
    pre(1);
    cout<<endl;
    mid(1);
    cout<<endl;
    hou(1);
    //cout<<endl;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值