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 106 107 108 109 110 111 112 113 114 115 116 117 118
| #include <stdio.h> #include <stdlib.h>
typedef char ElemType;
typedef struct TreeNode{ ElemType data; struct TreeNode *lchild; struct TreeNode *rchild; }TreeNode;
TreeNode* createNode(ElemType e) { TreeNode *p = (TreeNode*)malloc(sizeof(TreeNode)); p->data = e; p->lchild = NULL; p->rchild = NULL; return p; }
TreeNode* initTree() { TreeNode *root = createNode('A'); root->lchild = createNode('B'); root->rchild = createNode('C'); root->lchild->lchild = createNode('D'); root->lchild->rchild = createNode('E'); root->rchild->lchild = createNode('F'); root->rchild->rchild = createNode('G'); return root; }
void preOrder(TreeNode *root) { if(root == NULL) { return; } printf("%c ",root->data); preOrder(root->lchild); preOrder(root->rchild); }
void inOrder(TreeNode *root) { if(root == NULL) { return; } inOrder(root->lchild); printf("%c ",root->data); inOrder(root->rchild); }
void postOrder(TreeNode *root) { if(root == NULL) { return; } postOrder(root->lchild); postOrder(root->rchild); printf("%c ",root->data); }
int countNode(TreeNode *root) { if(root == NULL) { return 0; } return countNode(root->lchild) + countNode(root->rchild) + 1; }
int treeDepth(TreeNode *root) { if(root == NULL) { return 0; } int leftDepth = treeDepth(root->lchild); int rightDepth = treeDepth(root->rchild); return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1; }
void freeTree(TreeNode *root) { if(root == NULL) { return; } freeTree(root->lchild); freeTree(root->rchild); free(root); }
int main() { TreeNode *root = initTree(); preOrder(root); printf("\n"); inOrder(root); printf("\n"); postOrder(root); printf("\n"); printf("%d\n",countNode(root)); printf("%d\n",treeDepth(root)); freeTree(root); return 0; }
|