个人笔记(直接贴代码)
#include <cstdio>
#include <iostream>
#define maxn 110
using namespace std;
int f[maxn],l[maxn],r[maxn];
int v[maxn];
int n,t;
void init() { //建树
int p, k, lch, rch; //结点编号,权值,左右孩子指针
scanf( "%d", &n );
for( int i = 1; i <= n; i++ ) {
scanf( "%d%d%d%d", &p, &k, &lch, &rch );
v[p] = k;
l[p] = lch;
r[p] = rch;
if( lch ) f[lch] = p;
if( rch ) f[rch] = p;
}
}
int root() { //找根结点
for( int i = 1; i <= n; i++ ) {
if( f[i] == 0 )
return i;
}
}
void preorder( int i ) { //先序遍历
if( i ) {
printf( "%d ", v[i] );
preorder( l[i] );
preorder( r[i] );
}
}
void inorder( int i ) { //中序遍历
if( i ) {
inorder( l[i] );
printf( "%d ",v[i] );
inorder( r[i] );
}
}
void sucorder( int i ){ //后序遍历
if( i ) {
sucorder( l[i] );
sucorder( r[i] );
printf( "%d ", v[i] );
}
}
void leaf( int i ) { //输出叶结点
if( i ) {
if( l[i] + r[i] == 0 ) printf( "%d ", i );
leaf( l[i] );
leaf( r[i] );
}
}
int h( int i ) { //计算树的高度
if( i == 0 ) return 0;
return max( h( l[i] ), h( r[i] ) ) + 1;
}
void leaf( int i ) { //输出叶结点
if( i ) {
if( l[i] + r[i] == 0 ) printf( "%d ", i );
leaf( l[i] );
leaf( r[i] );
}
}
int h( int i ) { //计算树的高度
if( i == 0 ) return 0;
return max( h( l[i] ), h( r[i] ) ) + 1;
}
int main() {
freopen( "tree.in","r",stdin );
init();
t=root(); printf( "%d\n", t );
preorder( t ); printf( "\n" );
inorder( t ); printf( "\n" );
sucorder( t ); printf( "\n" );
leaf( t ); printf( "\n" );
printf( "%d\n", h( t ) );
return 0;
}