void CreatSeqTree(SeqTree tree, int i) { char ch; cin >> ch; if (ch == 'N') { return; } tree[i] = ch;
CreatSeqTree(tree, 2 * i); CreatSeqTree(tree, 2 * i + 1); } void InitSeqTree(SeqTree &tree) { memset(tree, 0, MAX_SIZE); }
SqStack InitStack(SqStack& S) { S.base = (Bitree*)malloc(sizeof(Bitree) * STACK_INIT_SIZE); S.top = S.base; S.stacksize = STACK_INIT_SIZE; return S; }
Bitree GetTop(SqStack S, Bitree &e) { if (S.top == S.base) { cout << "遍历结束"; exit(OVERFLOW); } e = *(S.top - 1); return e; }
bool Push(SqStack& S, Bitree &e) { if (S.top - S.base >= S.stacksize) { S.base = (Bitree*)realloc(S.base, (S.stacksize + STACKINCREASEMENT) * sizeof(Bitree)); S.top = S.base + S.stacksize; S.stacksize += STACKINCREASEMENT; } *S.top++ = e; return 1; } Bitree Pop(SqStack &S, Bitree &e) { if (S.top == S.base) return 0; e = *--S.top; return e; }
void CreateBitree(Bitree &T) {
char c; cin >> c; if (c == 'N') T = NULL; else { if (!(T = (BiNode*)malloc(sizeof(BiNode)))) exit(OVERFLOW); T->data = c; CreateBitree(T->lchild); CreateBitree(T->rchild); } }
bool PreOrder_print(Bitree T) { if (T) { cout << T->data << " "; if (PreOrder_print(T->lchild)) if (PreOrder_print(T->rchild)) return true; return false; } else return true; }
void InOrder_print(Bitree T, SqStack S) { Bitree P = T; Push(S, P); while (!(S.top - S.base == 0)) { while (GetTop(S, P) && P) Push(S, P->lchild); Pop(S, P); if (!(S.top - S.base == 0)) { Pop(S, P); cout << P->data << " "; Push(S, P->rchild); }
}
}
void LevelorderTraversal(Bitree BT) { if (BT == NULL) return; Bitree queue[100]; Bitree q; int tail = 0, head = 0; if (BT) { queue[tail++] = BT; while (head != tail) { q = queue[head++]; printf("%c ", q->data); if (q->lchild) queue[tail++] = q->lchild; if (q->rchild) queue[tail++] = q->rchild; }
} }
void InOrder_print2(Bitree T, SqStack S) { Bitree P = T; while (P || !(S.top - S.base == 0)) { if (P) { Push(S, P); P = P->lchild; } else { Pop(S, P); cout << P->data << " "; P = P->rchild; } } }
void InOrderTravel(Bitree T) { if (T == NULL) return; InOrderTravel(T->lchild); printf("%c ", T->data); InOrderTravel(T->rchild);
}
void TailOrderTravel(Bitree T) { if (T == NULL) return; TailOrderTravel(T->lchild); TailOrderTravel(T->rchild); printf("%c ", T->data); }
void preOrder(char *BT, int i) { if (BT[i] != 0) { printf("%c ", BT[i]); preOrder(BT, 2 * i); preOrder(BT, 2 * i + 1); } }
|