voidCreatBiTree(BiTree* T)// Function CreatBiTree create position for every node, so pass in the pointer. { // Also, lchild & rchild are both pointer, for the function can be valid with T and its children here needs a pointer points at BiTree rather than a single struct. char ch = ' '; printf("Print pre-order-traverse:\n"); scanf_s("%c", &ch, 8); setvbuf(stdin, NULL, _IOFBF, 512); if (ch == '#') { *T = NULL; } //'#' means the current node is an empty node. else{ *T = (BiNode*)malloc(sizeof(BiNode)); if (!*T) { printf("ERROR!\n"); } else { (*T)->data = ch; CreatBiTree(&(*T)->lchild); // Pay attention: pass in the address here. CreatBiTree(&(*T)->rchild); } } }
intDepth(BiTree T) { int m, n; if (T == NULL) { return0; } else { m = Depth(T->lchild); n = Depth(T->rchild); if (m > n) {return m + 1;} else{return n + 1;} }
voidInit_sq(SqStack* sta)// Functio Init spares memory for pointer base and top. { sta->base = (BiTree)malloc(100 * sizeof(BiTree)); if (!sta->base) { printf("error!"); } sta->top = sta->base = NULL; sta->stacksize = 100; }
voidPush(BiTree T, SqStack* sta) { if (sta->top - sta->base == sta->stacksize) { printf("ERROR! Stack is full.\n"); } else { sta->top->data = T->data; // Here 'sta->top = T' doesn't work because this will change the position of pointer top. sta->top->rchild = T->rchild; sta->top->lchild = T->lchild; sta->top++; } }
voidStackTraverseInOrder(BiTree T, SqStack* sta) { BiTree p = (BiNode*)malloc(sizeof(BiNode)); BiTree q = (BiNode*)malloc(sizeof(BiNode)); p = T; q = T; sta->top = sta->base = T; while (p || StackEmpty(sta) == 1) { if (p) { Push(p, sta); // Q1: Why sta->base changes after this step? A1: When the value of a pointer changes, the pointer's position changes. p = p->lchild; } else { q = Pop(q, sta); printf("%c ", q->data); p = q->rchild; } } }
voidEnQueue(SqQueue* que, BiNode* T) { // The method of using less than one spatial element is used to distinguish empty queues from full queues. if ((que->rear + 1) % MAXSIZE == que->front) { printf("Queue is full. Fail to insert.\n"); } else { que->data[que->rear] = *T; que->rear = (que->rear + 1) % MAXSIZE; // Make queue a circle. } }
BiTree DeQueue(SqQueue* que, BiTree T) { if (que->front == que->rear) { printf("Queue is empty.\n"); } *T = que->data[que->front]; que->front = (que->front + 1) % MAXSIZE; return T; }