二叉树的序遍历

2014-11-23 21:34:19 · 作者: · 浏览: 8
 
#include   
#include   
#include   
#include   
#include   
#include   
#include   
  
using namespace std;  
int a[ 20 ][ 3 ] ;  
void work1(int x)/////////////////////////////////////////////先序遍历     
{  
        printf("%d ",x);  
        if (a[x][1]!=0)   
            work1(a[x][1]);  
        if (a[x][2]!=0)   
            work1(a[x][2]);  
}  
          
void work2(int x) /////////////////////////////////////////////中序遍历    
{  
        if (a[x][1]!=0)  
            work2(a[x][1]);  
        printf("%d ",x);  
        if (a[x][2]!=0)   
            work2(a[x][2]);  
}  
          
void work3(int x)/////////////////////////////////////////////后续遍历   
{  
        if (a[x][1]!=0)   
            work3(a[x][1]);  
        if (a[x][2]!=0)   
            work3(a[x][2]);  
        printf("%d ",x);  
}  
  
int main()  
{  
    int n ;  
    while( scanf( "%d" , &n ) != EOF )  
    {  
        for( int i = 1 ; i <= n ; ++i )   
            scanf( "%d%d" ,&a[ i ][ 1 ] , &a[ i ][ 2 ] ) ;   
        work1( 1 ) ;  
        cout << endl ;  
        work2( 1 ) ;  
            cout << endl ;  
        work3( 1 ) ;   
            cout << endl ;  
    }  
    return 0 ;  
}