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

Suppose 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.

Input format:
Input the first line to give a positive integer n (≤1000), which is the maximum capacity of sequential storage; the second line to give n non-negative integers, separated by spaces. Where 0 represents an empty node in the binary tree (if the first node is 0, it represents an empty tree); the third row gives a pair of node numbers i and j.

Make sure that the input correctly corresponds to a binary tree, and 1≤i,j≤n.

Output format:
If i or j corresponds to an empty node, output ERROR: T[x] is NULL, where x is the number in i or j where the error was first found; otherwise, output numbers i and j in one line The number and value of the nearest common ancestor node of the two nodes are separated by a space.

Insert picture description here

Insert picture description here

Question idea:

The subscript of the parent node of each node (except the root node) of the binary tree is sequentially stored as i/2. Upload code

#include<iostream>
using namespace std;

int main()
{
    
    
	int ar[1001] = {
    
    0};
	int n;
	cin >> n; 
	for (int i = 1; i <= n; i++)
		cin >> ar[i];
	int a, b;
	cin >> a >> b;
	if (!ar[a]) 	
		printf("ERROR: T[%d] is NULL", a);
	else if (!ar[b])  
	  	printf("ERROR: T[%d] is NULL", b);
	else
	{
    
    
		while (a != b)
		{
    
    
			if (a > b) a /= 2;
			else b /= 2;
		}
		cout << a << " " << ar[a];
	}
    return 0;
}

Guess you like

Origin blog.csdn.net/xdg15294969271/article/details/113953327