当前位置:网站首页>寻找二叉树中任意两个数的公共祖先
寻找二叉树中任意两个数的公共祖先
2022-07-02 09:43:00 【weixin_50179990】
代码如下:
void Anales(int arr[],int p, int q)
{
int pos = -1;
int size = 0;
int as[1] = { 0 };
int indexP = 0;
int indexQ = 0;
while (arr[size] != as[1])
{
if (arr[size] == p)
{
indexP = size;
}
if (arr[size] == q)
{
indexQ = size;
}
size++;
}
if (indexP > indexQ)
{
int subInt = indexP - indexQ; //如索引的间隔正好等于更小的那个索引,那么它们的公//共祖先索引为0
if (subInt == indexQ)
{
pos = 0;
}
else
{
int fatherP = indexP;
while (fatherP > indexQ)
{
if (fatherP % 2) //如果当前索引为偶数,它的上一级 = (当前索引 - 2)/2
{
fatherP = (fatherP - 2) / 2;
}
else //如果当前索引为奇数,它的上一级 = (当前索引 - 1)/2
{
fatherP = (fatherP - 1) / 2;
}
}
if (fatherP == indexQ)
{
pos = fatherP;
}
else
{
//同时寻找上级直到相等
while (fatherP != indexQ)
{
if (fatherP % 2)
{
fatherP = (fatherP - 2) / 2;
}
else
{
fatherP = (fatherP - 1) / 2;
}
if (indexQ % 2)
{
indexQ = (indexQ - 2) / 2;
}
else
{
indexQ = (indexQ - 1) / 2;
}
}
pos = indexQ;
}
}
}
else if (indexQ > indexP)
{
int subInt = indexQ - indexP;
if (subInt == indexP)
{
pos = 0;
}
else
{
while (indexQ > indexP)
{
if (indexQ % 2)
{
indexQ = (indexQ - 2) / 2;
}
else
{
indexQ = (indexQ - 1) / 2;
}
}
if (indexP == indexQ)
{
pos = indexQ;
}
else
{
while (indexP != indexQ)
{
if (indexP % 2)
{
indexP = (indexP - 2) / 2;
}
else
{
indexP = (indexP - 1) / 2;
}
if (indexQ % 2)
{
indexQ = (indexQ - 2) / 2;
}
else
{
indexQ = (indexQ - 1) / 2;
}
}
pos = indexQ;
}
}
}
else
{
pos = indexP;
}
std::cout << "公共祖先:" << arr[pos] << "\t 索引:" << pos << std::endl;
}
int main()
{
int arr[15] = { 3,5,1,6,2,0,8,0,0,7,4,0,0,0,0 };
Anales(arr,5,4);
}
边栏推荐
猜你喜欢
Fresh, 2022 advanced Android interview must know 100 questions (interview questions + answer analysis)
SVO2系列之深度滤波DepthFilter
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
H5,为页面添加遮罩层,实现类似于点击右上角在浏览器中打开
Heap (priority queue)
【C语言】十进制数转换成二进制数
Natural language processing series (III) -- LSTM
ES集群中节点与分片的区别
倍增 LCA(最近公共祖先)
【2022 ACTF-wp】
随机推荐
ThreadLocal的简单理解
【工控老马】西门子PLC Siemens PLC TCP协议详解
CDA data analysis -- Introduction and use of aarrr growth model
深入理解P-R曲线、ROC与AUC
【C语言】杨辉三角,自定义三角的行数
[QT] Qt development environment installation (QT version 5.14.2 | QT download | QT installation)
WSL 2 will not be installed yet? It's enough to read this article
排序---
Depth filter of SvO2 series
JZ63 股票的最大利润
记录一下MySql update会锁定哪些范围的数据
使用Sqoop把ADS层数据导出到MySQL
[C language] convert decimal numbers to binary numbers
PyTorch搭建LSTM实现服装分类(FashionMNIST)
HR wonderful dividing line
自然语言处理系列(一)——RNN基础
(C language) 3 small Codes: 1+2+3+ · · +100=? And judge whether a year is a leap year or a normal year? And calculate the circumference and area of the circle?
Maximum profit of jz63 shares
Deep understanding of P-R curve, ROC and AUC
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL