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
| #include<stdio.h> #include<stdlib.h>
typedef struct BiTNode { char data; struct BiTNode *lchild, *rchild; }BiTNode, *BiTree;
void CreateBiTree(BiTree &T) { char ch; scanf("%c", &ch); if (ch == '#')T = NULL; else { T = (BiTree)malloc(sizeof(BiTNode)); T->data = ch; CreateBiTree(T->lchild); CreateBiTree(T->rchild); } }
void PreOrderTraverse(BiTNode *T) { if (T) { printf("%c", T->data); PreOrderTraverse(T->lchild); PreOrderTraverse(T->rchild); } }
void InOrderTraverse(BiTNode *T) { if (T) { InOrderTraverse(T->lchild); printf("%c", T->data); InOrderTraverse(T->rchild); } }
void PostOrderTraverse(BiTNode *T) { if (T) { PostOrderTraverse(T->lchild); PostOrderTraverse(T->rchild); printf("%c", T->data); } }
int GetLeavesCounts(BiTNode *T) { int Count = 0; if (!T)return 0; if (!T->lchild&&!T->rchild) { Count++; } else { Count += GetLeavesCounts(T->lchild); Count += GetLeavesCounts(T->rchild); } return Count; }
int GetBiTreeDepth(BiTNode *T) { if (!T)return 0; int LeftDepth = GetBiTreeDepth(T->lchild); int RightDepth = GetBiTreeDepth(T->rchild); return (LeftDepth > RightDepth) ? (LeftDepth + 1) : (RightDepth + 1); }
int main() { BiTree TreePointer; printf("Please Type the NODE of tree (type in ONE line):\n"); CreateBiTree(TreePointer); printf("\nPre-Order Traverse Result:\n"); PreOrderTraverse(TreePointer); printf("\nIn-Order Traverse Result:\n"); InOrderTraverse(TreePointer); printf("\nPost-Order Traverse Result:\n"); PostOrderTraverse(TreePointer); printf("\nTree Leaves Number:%d", GetLeavesCounts(TreePointer)); printf("\nTree Depth:%d\n", GetBiTreeDepth(TreePointer)); }
|