关于二叉树的建树

大致也就分两种,其中一种是静态建树,静态建树里面,可以是给每个点的子节点,也可以是给每个点的父节点,那种给先序/后续与中序来建树的就不说了,之说一下给出每个点父或子节点的情况。
1)只给出每个点的子节点:
8 1 -, - -, 0 -, 2 7, - -, - -, 5 -, 4 6
'-'表示无子节点;

	struct node{
    int l,r;
};
node arr[100];
bool isRoot[100]={0};
int change(char ch){//将‘-’转换为-1
    if(ch=='-')return -1;
    else{
        isRoot[ch-'0']=1;
        return ch-'0';
    }
}
int find_root(){//寻找根节点
    for(int i=0;i<n;i++)
        if(!isRoot[i])
            return i;
}
void creat(){//构建二叉树
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        char a,b;
        scanf("%*c%c %c",&a,&b);//*表示只读取不赋值给变量,此处用来读取无用的回车
        arr[i].l=change(a);
        arr[i].r=change(b);
    }
}

2)只给出每个点的子节点:
9 : 1 5 4 4 -1 4 5 3 6
这种情况看作是一个数组,每个位置存储着这个点的父节点,解决办法和上述大同小异。

struct node{
    int num[100];
    int index;
};
node arr[100];
void creat(){
    int n;
    int root;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        int temp;
        scanf("%d",&temp);
        if(temp==-1)
            root=i;
        else {
            arr[temp].num[index++]=i;
        }
    }
}
int maxdepth=0,num=0;
void dfs(int i,int depth){//顺带写了个深搜的求一下深度和最大深度的叶节点个数。
    if(arr[i].index==0){
        if(maxdepth<depth)
            maxdepth=depth,
            num=1;
        if(maxdepth==depth)
            num++;
        return ;
    }
    for(int j=0;j<arr[i].index;j++)
        dfs(arr[i].num[j],depth+1);
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值