#include <iostream>
#include <cstring>
using namespace std;
const int maxn= 1005;
struct Node{
char value;
int lchild, rchild;
Node(char v, int l, int r){
value = v;
lchild = l;
rchild = r;
}
Node(){
}
};
Node Tree[maxn];
int is_root[maxn];
void pre_order(int cur){
if(cur==0)
return;
cout<<Tree[cur].value;
pre_order(Tree[cur].lchild);
pre_order(Tree[cur].rchild);
}
int main(void){
int n;
while(cin>>n){
memset(Tree, 0, sizeof(Tree));
memset(is_root, 0, sizeof(is_root));
int number_mark, lc, rc;
char value;
for(int i=0; i<n; i++){
scanf("%d %c %d %d", &number_mark, &value, &lc, &rc);
Tree[number_mark] = Node(value, lc, rc);
is_root[lc] = 1;
is_root[rc] = 1;
if(is_root[number_mark] == 0)
is_root[number_mark] = -1;
}
int root;
for(int i=1; i<=1000; i++){
if(is_root[i] == -1){
root = i;
break;
}
}
pre_order(root);
cout<<endl;
}
}
// Node加设一个par域,则root节点的par为0。遍历找到root
#include <iostream>
#include <cstring>
using namespace std;
const int maxn= 1005;
struct Node{
char value;
int lchild, rchild;
Node(char v, int l, int r){
value = v;
lchild = l;
rchild = r;
}
Node(){
}
};
Node Tree[maxn];
int is_root[maxn];
void pre_order(int cur){
if(cur==0) return;
cout<<Tree[cur].value;
pre_order(Tree[cur].lchild);
pre_order(Tree[cur].rchild);
}
int main(void){
int n;
while(cin>>n){
memset(Tree, 0, sizeof(Tree));
memset(is_root, 0, sizeof(is_root));
int number_mark, lc, rc;
char value;
for(int i=0; i<n; i++){
scanf("%d %c %d %d", &number_mark, &value, &lc, &rc);
Tree[number_mark] = Node(value, lc, rc);
is_root[lc] = 1;
is_root[rc] = 1;
if(is_root[number_mark] == 0) is_root[number_mark] = -1;
}
int root;
for(int i=1; i<=1000; i++){
if(is_root[i] == -1){
root = i;
break;
}
}
pre_order(root);
cout<<endl;
}
}
// Node加设一个par域,则root节点的par为0。遍历找到root
转载请注明原文地址: https://ju.6miu.com/read-962456.html