建立一個二叉樹,求其高度,首先前、中、後序遍歷,求葉子數,求數的深度並且判斷是否爲平衡二叉樹。
#include<stdio.h>
#include<stdlib.h>
#define ERROR {puts("Error");return(1);}
// ERROR用於處理程序的運行錯誤
typedef struct BiTNode // 二叉樹要用的結構體
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree Create() // 創建二叉樹
{
char ch;
BiTree T;
ch=getchar();
if( ch == '#' )
T=NULL;
else
{
if( ! ( T = (BiTNode * )malloc( sizeof( BiTNode ) ) ) )
exit( 0 );
T->data = ch;
T->lchild = Create();
T->rchild = Create();
}
return T;
}
int preorder( BiTree T ) // 先序遍歷二叉樹
{
if( T )
{
printf( "%c" , T->data );
if( preorder( T->lchild ) )ERROR
if( preorder( T->rchild ) )ERROR
}
return 0;
}
int inorder( BiTree T ) // 中序遍歷二叉樹
{
if( T )
{
if( preorder( T->lchild ) )ERROR
printf( "%c" , T->data );
if( preorder( T->rchild ) )ERROR
}
return 0;
}
int postorder( BiTree T ) // 後序遍歷二叉樹
{
if( T )
{
if( preorder( T->lchild ) )ERROR
if( preorder( T->rchild ) )ERROR
printf( "%c" , T->data );
}
return 0;
}
int sumleaf( BiTree T ) // 求二叉樹葉子數
{
if( ! T )
return 0;
else
if( T->lchild || T->rchild )
return( sumleaf( T->lchild ) + sumleaf( T->rchild ) );
else
return 1;
}
int themax( int a, int b ) // 返回兩個整數中較大的一個
{
if( a>b )
return a;
else
return b;
}
int Depth( BiTree T ) // 求二叉樹的深度
{
if( !T )
return 0;
else
return( 1 + themax( Depth( T->lchild ), Depth( T->rchild ) ) );
}
bool bebalance(BiTNode *root)
{
if(root==NULL)
return true;
int ld=Depth(root->lchild);
int lr=Depth(root->rchild);
int di=abs(ld-lr);
if(di>1) //根節點平衡
return false;
return bebalance(root->lchild)&&bebalance(root->rchild); //左右子樹平衡
}
int main( int argc , char *argv[] ) // 測試用的主函數
{
BiTree T=Create(); // 創建樹
{ // 先序遍歷
printf("先序遍歷:");
if( preorder( T ) )
{
puts("ERROE!");
return 0;
}
else
printf("\n");
} // End_preorder.
{ // 中序遍歷
printf("中序遍歷:");
if( inorder( T ) )
{
puts("ERROE!");
return 0;
}
else
printf("\n");
} // End_inorder.
{ // 後序遍歷
printf("後序遍歷:");
if( postorder( T ) )
{
puts("ERROE!");
return 0;
}
else
printf("\n");
} // End_postorder.
printf( "The tree has %d leaves.\n" , sumleaf( T ) ); // 算葉子數
printf( "The Depth of the tree is %d.\n" , Depth( T ) ); // 求樹的深度 system( "pause" );
if(bebalance(T))
printf("the tree is balanced\n");
else
printf("the tree is unbalanced\n");
return 0;
}