小R的二叉树探险 | 模拟

问题描述

在一个神奇的二叉树中,结构非常独特:

每层的节点值赋值方向是交替的,第一层从左到右,第二层从右到左,以此类推,且该二叉树有无穷多层。

小R对这个二叉树充满了好奇,她想知道,在二叉树中两个节点之间x, y的路径长度是多少。

复制代码
graph TD
  1((1));2((2));3((3));4((4));
  5((5));6((6));7((7));8((8));
  9((9));10((10));11((11));
  1---3;1---2;3---4;3---5;
  2---6;2---7;6---11;6---10;
  7---9;7---8;

测试样例

示例 1:

输入:x = 11, y = 4

输出:5

示例 1:

输入:x = 2, y = 5

输出:3

示例 1:

输入:x = 7, y = 7

输出:0

题解:

因为每层的个数都是上一层乘二,同时是个,n为层数。所以就是x,y所在的层数。接着通过层高的奇偶性判断排列的顺序,再与x,y相减便可得到所在的位置。最后一层一层向上找相同的根即可得到路程。

代码:

cpp 复制代码
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#include <functional>
using namespace std;
typedef long long int ll;

int countplace(int dx,int x){
    int i,cnt=0;
    if(dx%2==1){
        return pow(2,dx)-(x-pow(2,dx));
    }
    else{
        return x-pow(2,dx)+1;
    }
}

int solution(int x, int y) {
    // write code here
    if(x<y){
        int tt=x;
        x=y;y=tt;
    }
    int i,j,k,t=max(x,y),maxi=0;
    int dx=0,dy=0,px=0,py=0,lx=0,ly=0;
    dx=log2(x);dy=log2(y);
    cout << dx << " " << dy << "\n";
    px=countplace(dx,x);
    py=countplace(dy,y);
    /*
    if(dx==dy){
        return abs(px-py);
    }
    */
    while(dx!=dy){
        if(px%2!=0){
            px++;
        }
        px/=2;dx-=1;lx++;
    }
    while(px!=py){
        if(px%2!=0){
            px++;
        }
        if(py%2!=0){
            py++;
        }
        px/=2;dx-=1;lx++;
        py/=2;dy-=1;ly++;
    }
    //cout << lx+ly << "\n";
    return lx+ly;
}

int main() {
    std::cout << (solution(11, 4) == 5) << std::endl;
    std::cout << (solution(2, 5) == 3) << std::endl;
    std::cout << (solution(7, 7) == 0) << std::endl;
    std::cout << (solution(383786261, 653995378)==57) << std::endl;
    std::cout << (solution(997295150, 889335947)==56) << std::endl;
    return 0;
}
相关推荐
程序媛小盐32 分钟前
贪心算法:最小生成树
算法·贪心算法·图论
Panesle34 分钟前
分布式异步强化学习框架训练32B大模型:INTELLECT-2
人工智能·分布式·深度学习·算法·大模型
c6lala44 分钟前
数据结构day1
数据结构
多多*1 小时前
算法竞赛相关 Java 二分模版
java·开发语言·数据结构·数据库·sql·算法·oracle
逐光沧海1 小时前
数据结构基础--蓝桥杯备考
数据结构·c++·算法·蓝桥杯
Kidddddult1 小时前
力扣刷题Day 48:盛最多水的容器(283)
算法·leetcode·力扣
AndrewHZ1 小时前
【Python生活】如何构建一个跌倒检测的算法?
python·算法·生活·可视化分析·陀螺仪·加速度计·跌倒检测
写个博客2 小时前
代码随想录算法训练营第三十九天
算法
源码方舟2 小时前
【基于ALS模型的教育视频推荐系统(Java实现)】
java·python·算法·音视频
吃个早饭3 小时前
2025年第十六届蓝桥杯大赛软件赛C/C++大学B组题解
c语言·c++·蓝桥杯