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
| #include <stdio.h> #include <stdlib.h>
typedef struct BiTNode { BiTNode* lchild, * rchild; char data; }BiTNode, * BiTree;
typedef struct LinkNode { BiTNode* data; LinkNode* next; }LinkNode;
typedef struct { LinkNode* front, * rear; }LinkQueue;
int InitQueue(LinkQueue& L) { L.front = L.rear = (LinkNode*)malloc(sizeof(LinkNode)); if (L.front == NULL) { return 0; } L.front->next = NULL; }
void PushNode(LinkQueue& L, BiTree T) { LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode)); s->data = T; s->next = NULL; L.rear->next = s; L.rear = s; }
void PopNode(LinkQueue& L, BiTree& T1) { T1 = L.front->next->data; printf("%c ", L.front->next->data->data); L.front = L.front->next; }
void LevelTraversal(BiTree& T) { BiTree T1; LinkQueue L; InitQueue(L); PushNode(L, T); while (L.front != L.rear) { PopNode(L, T1); if (T1->lchild != NULL) { PushNode(L, T1->lchild); } if (T1->rchild != NULL) { PushNode(L, T1->rchild); } } }
bool addLeftChild(BiTree root, char leftData) { BiTree leftNode = (BiTree)malloc(sizeof(BiTNode)); leftNode->data = leftData; leftNode->lchild = NULL; leftNode->rchild = NULL; root->lchild = leftNode; return true; }
bool addRightChild(BiTree root, char rightData) { BiTree rightNode = (BiTree)malloc(sizeof(BiTNode)); rightNode->data = rightData; rightNode->lchild = NULL; rightNode->rchild = NULL; root->rchild = rightNode; return true; }
int main() { BiTree root; root = (BiTree)malloc(sizeof(BiTNode)); root->data = 'A'; addLeftChild(root, 'B'); addRightChild(root, 'C'); addLeftChild(root->lchild, 'D'); addRightChild(root->lchild, 'E'); addLeftChild(root->rchild, 'F'); addRightChild(root->rchild, 'G');
LevelTraversal(root); }
|