1.队列实现
#include <cstdio>
#include <queue>
#define null NULL
using namespace std;
//事例:1 2 3 # # 4 # # 5 # #
//读取1作为根节点;1
//pop(1);读取2,作为lchild进队列;读取3作为rchild进队列;2 3
//pop(2);遇到#不进入if;遇到#不进入if;3
//pop(3);读取数字4作为lchild;遇到#不进入if;4
//pop(4);遇到#不进入if;读取数字5作为rchild;5
//pop(5);
struct treenode
{
treenode* rchild;
treenode* lchild;
int val;
treenode(int x)//构造函数
{
val=x;
rchild=lchild=null;
}
};
int main()
{
int x;
queue<treenode*> q;
scanf("%d",&x);//读取第一个数字
treenode* r=new treenode(x);//定义一个根结点root
q.push(r);//推入根节点
while(!q.empty())
{
treenode* cur=q.front();//拿到队首元素
q.pop();//弹出该元素
scanf("%d",&x);//读取下一个元素
if(x!=-1)//如果该元素不是#则
{
cur->lchild=new treenode(x);//即为左child
q.push(cur->lchild);//推入左child
}
scanf("%d",&x);//继续读入下一个元素
if(x!=-1)//如果该元素不是#则
{
cur->rchild=new treenode(x);//即为右child
q.push(cur->rchild);//推入右child
}
}
}
2.数组实现
//对于每棵树,首先在一行中给出一个非负整数n(<11),即该棵树的结点数(此时假设结点数从0到n-1编号);随后n行,第i行对应编号第i个结点
//给出该结点中存储的一个英文大写字母,其左孩子结点的编号,右孩子结点的编号。如果孩子结点为空,则在相应位置上给出-1。
//给出的数据间用一个空格隔开,题目保证每个结点中存储的字母是不同的
//8
//A 1 2
//B 3 4
//C 5 -1
//D -1 -1
//E 6 -1
//G 7 -1
//F -1 -1
//H -1 -1
#include <cstdio>
#include <cstring>
using namespace std;
struct treenode
{
char val;
int left;
int right;
treenode()//构造一个空函数,起到初始化作用
{
left=right=-1;
}
treenode(char x)
{
val = x;
left=right=-1;
}
};
//放在int main()作为全局变量,外部自动初始化
treenode a[200];
int indepth[200]={0};
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
char val;
int l,r;
getchar();//避免回车影响
scanf("%c %d %d",&val,&l,&r);
a[i].left=l;
if(l!=-1)
indepth[l]++;//非根结点位置不为0
a[i].right=r;
if(r!=-1)
indepth[r]++;//非根结点位置不为0
a[i].val=val;
}
int rdepth = -1;
for(int i=0;i<n;i++)
{
if(!indepth[i])//位置为0,即为根结点
rdepth = i;
}
printf("root:%d\n",rdepth);//root:0
}