二叉树的基本操作,求高度,叶子数,结点数等
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 typedef struct node 5 { 6 struct node *left, *right; 7 char data; 8 9 }BiTreeNode, *BiTree; 10 void createBiTree(BiTree &T) 11 { 12 char c; 13 cin >> c; 14 if ('#' == c) 15 { 16 T = NULL; 17 } 18 else 19 { 20 T = new BiTreeNode; 21 T->data = c; 22 createBiTree(T->left); 23 createBiTree(T->right); 24 } 25 } 26 void leveltraverse(BiTree T) 27 { 28 queue<BiTree> que; 29 BiTree p = T; 30 if (p) 31 { 32 que.push(p); 33 } 34 while (!que.empty()) 35 { 36 p = que.front(); 37 que.pop(); 38 cout << p->data << " "; 39 if (p->left!=NULL) 40 { 41 que.push(p->left); 42 } 43 if (p->right != NULL) 44 { 45 que.push(p->right); 46 } 47 } 48 } 49 //求结点总数 50 int size(BiTree T) 51 { 52 if (T==NULL) 53 { 54 return 0; 55 } 56 return 1+ size(T->left) + size(T->right); 57 } 58 //求高度 59 int height(BiTree T) 60 { 61 if (T == NULL) 62 { 63 return 0; 64 } 65 else 66 { 67 int lh = height(T->left), rh = height(T->right); 68 return 1 + ((lh > rh) ? lh : rh); 69 } 70 } 71 //求叶子数 72 int leafnum(BiTree T) 73 { 74 if (T==NULL) 75 { 76 return 0; 77 } 78 else if ((T->left==NULL)&&(T->right==NULL)) 79 { 80 return 1; 81 } 82 else 83 { 84 return leafnum(T->left) + leafnum(T->right); 85 } 86 } 87 //求只有一个孩子的结点的个数 88 void count(BiTree T, int *sum) 89 { 90 if (T!=NULL) 91 { 92 if ((T->left==NULL)&&(T->right!=NULL)|| (T->left != NULL) && (T->right == NULL)) 93 { 94 (*sum)++; 95 //return; 96 } 97 count(T->left, sum); 98 count(T->right, sum); 99 } 100 } 101 int main() 102 { 103 BiTree T; 104 cout << "按照前序顺序建立二叉树" << endl; 105 createBiTree(T); 106 cout << "二叉树创建完成" << endl; 107 cout << "层次遍历输出" << endl; 108 leveltraverse(T); 109 cout << endl; 110 cout << "其结点总数为:" << size(T); 111 cout << endl; 112 cout << "其高度为:" << height(T); 113 cout << endl; 114 cout << "其叶子数为:" << leafnum(T); 115 cout << endl; 116 int sum = 0; 117 count(T,&sum); 118 cout <<"只有一个孩子结点的个数为:"<< sum; 119 }
道阻且长,行则将至

浙公网安备 33010602011771号