// Combine the two public sectors holding ancestors into one // Merged ancestors, the order is reversed, that is, the last one is the most recent ancestor 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; } } // Find the common ancestor idea of two nodes, use post-order non-recursive algorithm // Use two auxiliary stacks, one stack to save void printCommonAncestor(BTNode *root, char y, char z) { if (root != nullptr) { int tag[20]; // mark whether the right subtree of each node has been visited BTNode *stack[maxsize]; char stacky[20], stackz[20]; // Auxiliary stack, keep the ancestor of node y and the ancestor of node 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) { // Copy the rest of the stack to 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; } } // Finally, stacky and stackz save their ancestors char commonAncestor[maxsize]; mergeCommon (commonAncestor, stacks, stackz, tops, topz); printf(""); } }
Common ancestor of binary tree
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325642072&siteId=291194637
Recommended
Ranking