Zhejiang University Edition "Data Structure (Second Edition)" Question Collection-Exercise 4.5

Exercise 4.5 The nearest common ancestor problem of a binary tree stored sequentially (25point(s))

Assuming that there are two nodes numbered i and j in the binary tree stored sequentially, please design an algorithm to find the number and value of their nearest common ancestor node.

Example:

#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;

#define CHECK(x) if(H[x]==0) {printf("ERROR: T[%d] is NULL\n", x);return 0;}
#define MARK(x)  {int h=x;while(h){V[h]+=1;h>>=1;}}

int main()
{
    int N;
    cin >> N;
    vector<int> H;
    vector<int> V;
    H.reserve(N+1);
    V.reserve(N+1);
    for(int k = 1; k <= N; k++) {
        cin >> H[k];
        V[k] = 0;
    }
    int i, j;
    cin >> i >> j;
    CHECK(i);
    CHECK(j);
    MARK(i);
    MARK(j)
    while(i) {
        if(V[i] == 2) { cout << i << ' ' << H[i] << endl; break;}
        i >>= 1;
    }
    return 0;
}

Ideas:

Mark the path from i, j to the root node, and then recheck the path from i or j. If a node is marked twice, then this is the common ancestor

Guess you like

Origin blog.csdn.net/u012571715/article/details/113308211