void PreOrder(BTNode* b) { BTNode* p; BTNode* St[MAXSIZE]; int top = -1; p = b; while (p != NULL || top != -1) { while (p != NULL) { printf("%c ", p->data); St[++top] = p; p = p->lchild; } if (top != -1) { p = St[top--]; p = p->rchild; } } }
void InOrder(BTNode* b) { BTNode* p; BTNode* St[MAXSIZE]; int top = -1; p = b; while (p != NULL || top != -1) { while (p != NULL) { St[++top] = p; p = p->lchild; } if (top != -1) { p = St[top--]; printf("%c", p->data); p = p->rchild; } } }
如何判断p的右子树已遍历过,是算法的重要难点。
void PostOrder(BTNode* b) { BTNode* p, * r; BTNode* St[MAXSIZE]; int top = -1; p = b; bool flag = true; do { while (p != NULL) { St[++top] = p; p = p->lchild; } r = NULL; flag = true; while (flag && top != -1) { p = St[top]; if (p->rchild == r) { printf("%c", p->data); top--; r = p; } else { p = p->rchild; flag = false; } } } while (top!=-1); }
void LevelOrder(BTNode* b) { BTNode* p = b; BTNode* qu[MAXSIZE]; int front = -1; int rear = -1; qu[++rear] = p; while (rear != front) { p = qu[++front]; printf("%c", p->data); if (p->lchild) qu[++rear] = p->lchild; if (p->rchild) qu[++rear] = p->rchild; } }