-->
当前位置:首页 > 题库

PROGRAMMING:Tree's nearest common ancestor

Luz5年前 (2021-05-10)题库425
It is known that tree nodes are not equal to each other and are not equal to 0 integers. Please write a program to find the nearest common ancestor of two nodes in the non empty tree. For example, for the tree T shown in Figure 1 (a), the nearest common ancestor of nodes 1 and 2 is 5; The nearest common ancestor of nodes 2 and 4 is 8.
![ tree.jpg](~/43e51246-40dc-4ad6-99f3-df4fad65f182.jpg)
###Input format:
The input is 2 lines, the first line is a group of integers separated by spaces, the number of which is no more than 100, indicating the first root sequence of binary tree with null pointer information. The null pointer information is represented by 0. In the second line, two mutually unequal integers a and B with space interval represent the given two node values to ensure that a and B are definitely in the input tree.
Note: we know that the left child of the node in the binary tree corresponds to the left child of the node in the tree, and the right child of the node in the binary tree corresponds to the right brother of the node in the tree. Furthermore, we can construct the left child right brother storage structure of the corresponding tree by using the method of "constructing binary tree with the first root sequence with null pointer information". As shown in Figure 1 (a), 8 5 10 6 0 2 0 3 4 0 7 0 0 0 0 0 0 0 corresponds to the tree as shown in Figure 1 (b).
###Output format:
The output is an integer representing the value of the nearest common ancestor node of a and B.
###Input sample 1:
```in
8 5 1 0 6 0 2 0 0 3 4 0 0 7 0 0 0
1 2
```
###Output sample 1:
```out
five
```
###Input sample 2:
```in
8 5 1 0 6 0 2 0 0 3 4 0 0 7 0 0 0
2 4
```
###Output sample 2:
```out
eight
```






answer:If there is no answer, please comment