[笔记]: 树转二叉树

28 篇文章 0 订阅
25 篇文章 0 订阅

给出一个多叉树
那么怎么将树转换为一个二叉树呢?

/*
树-->二叉树
    给出一棵树 将此树转化为二叉树
采用兄弟表示法 
如给出:
       A
    B  C  D
   E F
转化为:
      A
    B
  E   C
   F   D
转换方法
将 树的 最左结点作为二叉树的左节点 从第二个结点开始(左节点的兄弟) 作为二叉数中的右儿子 
如例子中的 c是b的兄弟 所以二叉树中b的右儿子是c d是c的兄弟  所以二叉树中c的右儿子是d
二叉树左边是树的左边第一个结点 兄弟都在右子树上 
依次类推 

因为树没有中序遍历 只有先序和后序
有一规律:
    用此做法得出的二叉树 
    先序遍历是树的先序遍历
    中序遍历是树的后序遍历 
样例输入:
    6
    A 3 2 3 4
    B 2 5 6
    C 0
    D 0
    E 0
    F 0 
第一个数字n表示n个结点
后面n行 
第i行代表结点编号是i 
每行 第一个字符ch表示结点代号 第二个是数字p代表有几个结点  后面p个数表示结点的子结点的编号 
*/ 
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
struct node{
    char data;
    int left;
    int right;
}tree[1000];
int temp;
void insert(int pd,int bh){
    if(pd==1){//左儿子
        tree[temp].left=bh;
        temp=bh;
    }
    else {
        tree[temp].right=bh;
        temp=bh;
    }
}
void dfs1(int s){ 
    cout<<tree[s].data<<" ";
    if(tree[s].left)    dfs1(tree[s].left);
    if(tree[s].right)   dfs1(tree[s].right);
}
void dfs2(int s){
    if(tree[s].left)    dfs2(tree[s].left);
    cout<<tree[s].data<<" ";
    if(tree[s].right)   dfs2(tree[s].right);
}
int main(){
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        getchar();
        char x;
        int t;
        scanf("%c%d",&x,&t);
        tree[i].data=x;
        temp=i;
        for(int j=1;j<=t;j++){
            int p;
            scanf("%d",&p);
            insert(j,p);
        }
    }
    cout<<"先序遍历:"; 
        dfs1(1);
    cout<<endl;
    cout<<"中序遍历: ";
        dfs2(1);
    cout<<endl; 
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值