1. 程式人生 > 實用技巧 >二叉樹—課上課後練(4

二叉樹—課上課後練(4

 1 #include <iostream>
 2 using namespace std;
 3 
 4 typedef char DataType;
 5 
 6 //二叉樹資料結構 
 7 struct node
 8 {
 9     DataType info ; //存放結點資料 
10     struct node *lchild , *rchild ; //指向左右孩子的指標 
11 };
12 
13 typedef struct node *BiTree ;
14 
15 /*建立二叉樹
16   函式名:createBiTree
17   引數:無
18   返回值:二叉樹根結點指標
19 */ 20 BiTree createBiTree(void) 21 { 22 char ch ; 23 BiTree root ; 24 cin>>ch ; 25 if(ch == '#') root = NULL; 26 else{ 27 root = new struct node ; 28 root->info = ch ; 29 root->lchild = createBiTree() ; 30 root->rchild = createBiTree();
31 } 32 return root ; 33 } 34 35 void visit(BiTree T) 36 { 37 cout<<T->info ; 38 } 39 40 int countFullNode(BiTree root) 41 { 42 //請在此處填寫程式碼,計算二叉樹中滿結點的個數 43 /********** Begin **********/ 44 int nodes = 0; 45 if(root == NULL) 46 return 0; 47 else if(root->lchild== NULL && root->rchild == NULL)
48 return 0; 49 else if(root->lchild == NULL && root->rchild!= NULL) 50 nodes = countFullNode(root->rchild); 51 else if(root->lchild != NULL && root->rchild == NULL) 52 nodes = countFullNode(root->lchild); 53 else 54 nodes = 1+countFullNode(root->lchild) + countFullNode(root->rchild); 55 return nodes; 56 57 /*********** End-**********/ 58 } 59 60 int main(void) 61 { 62 BiTree root = createBiTree(); 63 cout<<countFullNode(root) ; 64 }
View Code