当前位置:网站首页>寻找二叉树中任意两个数的公共祖先
寻找二叉树中任意两个数的公共祖先
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);
}

边栏推荐
猜你喜欢

How to Create a Beautiful Plots in R with Summary Statistics Labels

自然语言处理系列(一)——RNN基础

HOW TO ADD P-VALUES TO GGPLOT FACETS

YYGH-9-预约下单

Natural language processing series (II) -- building character level language model using RNN

GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT

Mish shake the new successor of the deep learning relu activation function

Take you ten days to easily finish the finale of go micro services (distributed transactions)

CDH存在隐患 : 该角色的进程使用的交换内存为xx兆字节。警告阈值:200字节

SVO2系列之深度濾波DepthFilter
随机推荐
QT meter custom control
基于Arduino和ESP8266的Blink代码运行成功(包含错误分析)
还不会安装WSL 2?看这一篇文章就够了
Applet link generation
堆(優先級隊列)
Read the Flink source code and join Alibaba cloud Flink group..
【C语言】十进制数转换成二进制数
Leetcode122 the best time to buy and sell stocks II
Input a three digit number and output its single digit, ten digit and hundred digit.
倍增 LCA(最近公共祖先)
Repeat, tile and repeat in pytorch_ The difference between interleave
Leetcode739 每日温度
Sort---
YYGH-BUG-05
Mish shake the new successor of the deep learning relu activation function
YYGH-9-预约下单
mysql表的增删改查(进阶)
二分刷题记录(洛谷题单)区间的甄别
Tas (file d'attente prioritaire)
Easyexcel and Lombok annotations and commonly used swagger annotations