// 將兩個保存祖先的公共部門組合併成一個 // 合併後的祖先,順序是反的,就是最後一個纔是最近的祖先 void mergeCommon(char stack[], char stack1[], char stack2[], int top1, int top2) { for (int i = 0; i <= top1 && i <= top2; i++) { if (stack1[i] == stack2[i]) { stack[i] = stack1[i]; } else { break; } } } void copyStack(BTNode *stack1[], char stack2[], int top) { for (int i = 0; i <= top; i++) { stack2[i] = stack1[i]->data; } } // 尋找兩個節點的共同祖先 思路,用後序非遞歸算法 // 用兩個輔助棧,一個棧保存 void printCommonAncestor(BTNode *root, char y, char z) { if (root != nullptr) { int tag[20]; // 標記每一個節點的右子樹是否被訪問過 BTNode *stack[maxsize]; char stacky[20], stackz[20]; // 輔助棧,保留節點y的祖先和節點z的祖先 int topy = -1, topz = -1; int top = -1; BTNode *q; q = root; while (q != nullptr || top != -1) { while (q != nullptr) { stack[++top] = q; q = q->left; tag[top] = 0; } while (top != -1 && tag[top] == 1) { q = stack[top--]; if (q->data == y) { // 將棧裏面剩餘的複製到stacky裏面 copyStack(stack, stacky, top); topy = top; } if (q->data == z) { copyStack(stack, stackz, top); topz = top; } } if (top != -1) { tag[top] = 1; q = stack[top]; q = q->right; } else { break; } } // 最後stacky 和 stackz裏面保存的都是各自的祖先 char commonAncestor[maxsize]; mergeCommon(commonAncestor, stacky, stackz, topy, topz); printf(""); } }