普通树或有向图转二叉树

//转二叉树
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
struct Node{
int l,r;
};

vector<int>E[310];//图的邻接表
int score[310],brother[310],n,m;//学分, n总课程树量,m 选课数
bool vist[310];
Node tree[310];//二叉树

void DfsTree(int v)
{
vist[v]=1;
cout<<"a"<<endl;
if (E[v].size()>0) tree[v].l=E[v][0];
tree[v].r=brother[v];
for(int i=0;i<E[v].size();i++)
if(!vist[E[v][i]]) DfsTree(E[v][i]);
}

int main()
{
scanf("%d%d",&n,&m);//n总课程数,m 选课数
int i,father,s;
for(i=1;i<=n;i++)//建立邻接表
{
scanf("%d%d",&father,&s);
E[father].push_back(i);
score[i]=s;
}
for(i=0;i<=n;i++)
brother[i]=tree[i].l=tree[i].r=-1;

for(i=0;i<=n;i++)//遍历邻接表,为每个节点找右边的兄弟
for(int j=0;j<E[i].size()-1;j++)
{
cout<<endl<<i;
brother[E[i][j]]=E[i][j+1];
cout<<endl<<E[i][j];
}

// DfsTree(0);
/*
for(i=0;i<=n;i++)
{
cout<<i<<":";
for(int j=0;j<E[i].size();j++)
cout<<E[i][j]<<" ";
cout<<endl;
}
for(i=0;i<=n;i++)
cout<<i<<" "<<tree[i].l<<" "<<tree[i].r<<endl;
*/
}
/*
7 4
2 2
0 1
0 4
2 1
7 1
7 6
2 2

*/
/*

*/

原文地址:https://www.cnblogs.com/StoneXie/p/9584313.html