1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include<stdio.h> #include<stdlib.h> #include<malloc.h> #define ERROR -1 typedef char DataType; typedef struct TreeNode { DataType elem; struct TreeNode* rchild; struct TreeNode* lchild; }TreeNode, *PTREE;
void CreatTree(PTREE *Root) { char val = 0; val = getchar(); if (val == '*'|| val == '#' || val == '.') (*Root) = NULL; else { (*Root) = (PTREE)malloc(sizeof(TreeNode)); if ((*Root) == NULL) { printf("创建结点失败,无法分配可用内存..."); exit(-1); } else { (*Root)->elem = val; CreatTree(&(*Root)->lchild); CreatTree(&(*Root)->rchild); } } }
void PreOrderTree(PTREE Root) {
if (Root == NULL) return; else { putchar(Root->elem); PreOrderTree(Root->lchild); PreOrderTree(Root->rchild); } }
int GetNodeNum(PTREE Tree) { if (NULL == Tree) { return 0; } else { return GetNodeNum(Tree->lchild) + GetNodeNum(Tree->rchild) + 1; } }
int GetLeafNum(PTREE Tree) { if (Tree == NULL) return 0; if (Tree->lchild == NULL&&Tree->rchild == NULL) return 1; return GetLeafNum(Tree->lchild) + GetLeafNum(Tree->rchild); }
int GetNodde1Num(PTREE Tree) { if (Tree == NULL)
return 0;
if (Tree->lchild == NULL&&Tree->rchild != NULL || Tree->rchild == NULL&&Tree->lchild != NULL)
return 1 + GetNodde1Num(Tree->lchild) + GetNodde1Num(Tree->rchild); return GetNodde1Num(Tree->lchild) + GetNodde1Num(Tree->rchild); }
int GetNodde2Num(PTREE Tree) { if (Tree == NULL) return 0; if (Tree->lchild != NULL&&Tree->rchild != NULL) return 1+ GetNodde2Num(Tree->lchild) + GetNodde2Num(Tree->rchild); return GetNodde2Num(Tree->lchild) + GetNodde2Num(Tree->rchild); } int main(void) { PTREE root; printf("请输入前序 *或#或.为空\t"); CreatTree(&root); printf("前序遍历 :\t"); PreOrderTree(root); printf("\n"); printf("递归求所有结点 %d\n", GetNodeNum(root)); printf("等式求所有结点 %d\n", GetLeafNum(root)+ GetNodde2Num(root) + GetNodde1Num(root)); printf("递归求所有叶子结点 %d\n", GetLeafNum(root)); printf("性质求所有叶子结点 %d\n", GetNodde2Num(root)+1); printf("递归求所有度为1的结点 %d\n", GetNodde1Num(root)); printf("等式求所有度为1的结点 %d\n", GetNodeNum(root)- GetLeafNum(root)- GetNodde2Num(root)); printf("递归求所有度为2的结点 %d\n", GetNodde2Num(root)); printf("性质求所有度为2的结点 %d\n", GetLeafNum(root)-1); printf("总结: 根据书中的性质3和一个等式,只要有两个数据(度2和度0算一个),其他数据都可以算出\n"); system("pause"); return 0; }
|