二叉树的建树方法

1.数组建树给一个普通序列:567432

#include<stdio.h>
#include<string.h>

int tree1[300010];
int s[300010];
int n;

void Insert(int w,int *tree)
{
    int c=w;
    int now=1;
    while(tree[now]!=-1)//没有被赋值
    {
        if(tree[now] < c)//当前数比数根大
            now = now*2 + 1;//右孩子
        else
            now = now*2;//左孩子
    }
    tree[now] = c;
}

void build(int *s,int *tree)
{
    tree[1] = s[0] ;
    for(int i = 1 ; i < n ; i++)
        Insert(s[i],tree);
}

int main()
{
    scanf("%d",&n);
    memset(tree1,-1,sizeof(tree1));
    for(int i=0; i<n; i++)
        scanf("%d",&s[i]);
    build(s,tree1);
    return 0;
}

2.使用链表建树,前序遍历输出

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;

typedef struct node
{
    int data;
    node *lchild,*rchild;
}*Tree,tree;

Tree root;
int n;

void insert(Tree& root , int t)
{
    if(root==NULL)//如果为空==没有被赋值
    {
        root = (Tree)malloc(sizeof(tree));//开辟一个新单元
        root->data = t;
        root->lchild = NULL;
        root->rchild = NULL;
    }
    else if(t < root->data)//当前数比树根小是左孩子,否则是右孩子
    {
        insert(root->lchild , t);//左孩子
    }
    else insert(root->rchild , t);//右孩子
}

void preoder(Tree root,int& cnt)//先序遍历
{
    if(root==NULL)
        return ;
    cnt++;   //用于控制输出格式
    if(cnt!=n)
        printf("%d ",root->data);
    else
        printf("%d\n",root->data);
    preoder(root->lchild,cnt);
    preoder(root->rchild,cnt);
}

int main()
{
    scanf("%d",&n);
    int t;
    for(int i=0; i<n; i++)
    {
        scanf("%d",&t);
        insert(root,t);//建树
    }
    int cnt=0;
    preoder(root,cnt);//先序遍历
    return 0;
}


  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值