Leetcode 236. Lowest Common Ancestor of a Binary Tree

图解LeetCode236:Lowest Common Ancestor of a Binary Tree 文章目录如何确定两个节点的公共节点?代码实现总结 二叉树最低公共祖先节点又是一道极为经典的算法题,同时也是面试官几乎用烂的一个题目,准备跳槽找工作的同学必知必会的一个面试题。 这个题目的要求非常简单,求出给定两个二叉树节点的公共祖先,如下所示的二叉树,那么节点5和节点1的3,我们该怎样解决这个问题呢?   如何确定两个节点的公共节点? 这个问题的关键点在于我们怎么就能确定某个节点是给定... 阅读详情

Leetcode 236. Lowest Common Ancestor of a Binary Tree

source url

题目描述

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

输入:树的根root,以及两个树的节点p,q
输出:上述该两个节点的最小公共祖先节点

思路

遍历与回溯:如题目所示,首先对整个树进行深度优先遍历一遍,并记录对应搜索节点所在的层数pl、ql,以及每个节点的前置节点prev。而后根据DFS结果进行回溯。
1. 若pl==ql,若prev[p]==prev[q]则返回prev[q]。否则,搜索节点进行回溯

if(pl==ql){
       if(prev[tp]==prev[tq]){
            return prev[tp];
        }else{
            pl--;
            ql--;
            tp = prev[tp];
            tq = prev[tq];
        }
}
  1. 若pl>ql,那么有可能q是p的祖先,否则回溯p;反之亦然。
            }else if(pl>ql){
                if(tq==prev[tp]){
                    return tq;
                }else{
                    pl--;
                    tp = prev[tp];
                }
            }else if(pl<ql){
                if(tp==prev[tq]){
                    return tp;
                }else{
                    ql--;
                    tq = prev[tq];
                }
            }

DFS复杂度 O(n) ,回溯复杂度 O(n)

代码

class Solution {
public:
    unordered_map<TreeNode*,TreeNode*> prev;
    int pl=0,ql=0;
    int level = 0;
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* temp = root;
        TreeNode* tp = p;
        TreeNode* tq = q;
        prev[root] = root;
        dfs(temp,p,q);
        while(pl>=0&&ql>=0){
            if(pl==ql){
                if(prev[tp]==prev[tq]){
                    return prev[tp];
                }else{
                    pl--;
                    ql--;
                    tp = prev[tp];
                    tq = prev[tq];
                }
            }else if(pl>ql){
                if(tq==prev[tp]){
                    return tq;
                }else{
                    pl--;
                    tp = prev[tp];
                }
            }else if(pl<ql){
                if(tp==prev[tq]){
                    return tp;
                }else{
                    ql--;
                    tq = prev[tq];
                }
            }

        }

        return root;
    }

    void dfs(TreeNode* root, TreeNode* p, TreeNode* q){
        if(root==NULL||p==NULL||q==NULL){
            return;
        }
        if(root==p){
            pl = level;
        }
        if(root==q){
            ql = level;
        }


        if(root->left!=NULL){
            prev[root->left] = root;
            level++;
            dfs(root->left,p,q);
            level--;
        }

        if(root->right!=NULL){
            prev[root->right] = root;
            level++;
            dfs(root->right,p,q);
            level--;
        }

    }
};
IEEE LaTeX模板中algorithm排版避坑指南:如何优雅地嵌入算法描述? 本文详细解析了在IEEE LaTeX模板中优雅排版algorithm的实用技巧,包括基础配置、高级自定义及常见问题解决方案。通过嵌套环境与[H]参数的应用,帮助研究者克服IEEEtran模板对算法排版的限制,实现专业且美观的算法呈现。 阅读详情

相关推荐

ERA5数据批量下载

ERA5再分析数据的IDM接管下载

qq_38734327的博客 3037

leetcode 236. Lowest Common Ancestor of a Binary Tree(python)

leetcode 236. Lowest Common Ancestor of a Binary Tree题目解法1:DFS解法2:BFS+字典参考 题目 Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.According to the definition of L...

qq_37821701的博客 493

运放 + MOS管构成的恒流电路分析及实用环境器件参数选择

恒流电路

五花带点肉 2万+

LeetCode 236. Lowest Common Ancestor of a Binary Tree 题解

本题是二叉树的经典问题,主要考察对树的遍历和递归的理解。递归深度优先搜索:代码简洁易懂,逻辑清晰,是最直观的解决方案。迭代后序遍历:避免了递归的栈溢出问题,适用于深度较大的树,但代码相对复杂。在实际应用中,递归方法通常是最首选的解决方案,因为它代码简洁且易于理解。但在处理深度较大的树时,迭代方法可能更为可靠。无论使用哪种方法,核心思想都是相同的:找到两个节点的路径,然后找到它们的最近公共祖先。

cannonjinx的博客 2276

STM32串口接收避坑指南:为什么你的USART_IT_IDLE中断不触发?附完整调试流程

本文深入解析STM32串口接收中断机制,特别是USART_IT_IDLE中断不触发的常见原因及解决方案。通过详细分析中断标志清除顺序、波特率配置、硬件连接等关键因素,并提供完整的调试流程和代码示例,帮助开发者快速定位并解决串口通信问题。

weixin_42519985的博客 349

告别米级误差:手把手教你用Nordic nRF52840实现厘米级蓝牙测距(Channel Sounding实战)

本文详细介绍了如何利用Nordic nRF52840开发板和蓝牙信道探测(Channel Sounding)技术实现厘米级高精度测距。通过硬件配置、软件优化和实战案例,帮助开发者快速掌握低功耗蓝牙测距技术,适用于工业自动化、智能仓储等场景。

weixin_42741930的博客 479

leetcode 236: Lowest Common Ancestor of a Binary Tree

leetcode 236: Lowest Common Ancestor of a Binary Tree PYTHON, JAVA, C++

西施豆腐渣 7625

opencv的cmake报错

1、下载 ippicv_2021.8_win_intel64_20230330_general.zip、v0.1.2a.zip、opencv_videoio_ffmpeg.dll、opencv_videoio_ffmpeg_64.dll、ffmpeg_version.cmake。由于下载源在https://raw.githubusercontent.com,由于网络原因下载不顺畅,可以先找到文件下载到对应文件夹下,或者更改网络环境。ffmpeg_version.cmake文件,打开后显示如下, 另存即可。

nownow_的博客 1300

[LeetCode 236] Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two node

coder 进阶的专栏 3260

Veeam Backup Replication Console 13 备份 PVE

本文介绍了如何通过Veeam Backup & Replication控制台配置与Proxmox VE(PVE)服务器的连接,包括主机地址、用户名密码和SSH信任设置。随后详细说明了部署备份Worker虚拟机的步骤,涵盖网络配置和VM创建。接着指导用户创建PVE虚拟机备份任务,包括命名、选择备份对象、存储位置、备份类型设置,以及配置备份计划任务。最后描述了备份测试执行过程,从启动备份到完成状态通知的完整流程。整个操作涉及服务器连接、Worker部署、备份配置和任务执行四个主要环节。

极致,细节 1610

C++控制台实现简单的注册登录

C++控制台实现简单的注册登录 #include<iostream> #include<string> #include <vector> #include <conio.h> void Display();//调用display显示switch()界面 void Register();//注册 void Enter();//登录 using nam...

乔路非 2万+

Leetcode 236. Lowest Common Ancestor of a Binary Tree

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ cla...

BJUT_bluecat的博客 286

深度剖析:Spring AI 与 LangChain4j,谁才是 Java 程序员的 AI 开发利器?

首先介绍 AI 时代 Java 开发框架选择背景,接着对比两者功能特性(Spring AI 的生态集成与标准化设计、LangChain4j 的多模型适配与提示工程)、应用场景(企业级系统改造与创新产品开发)、开发体验(学习成本与调试工具)、生态扩展(Spring 商业支持与 LangChain4j 开源社区)、性能安全(企业级优化与自主安全实现)及成本趋势(短期投入、长期回报与技术演进),最后给出选型建议与混合架构方案。

博客 5446

Leetcode 236 Lowest Common Ancestor of a Binary Tree

Leetcode 236 Lowest Common Ancestor of a Binary Tree 题目描述 Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “T...

qq_43271202的博客 218

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

[leetcode] 236. Lowest Common Ancestor of a Binary Tree @ python

原题 https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ 解法 参考: LeetCode 236 Lowest Common Ancestor of a Binary Tree 【公瑾讲解】 使用递归, base case是返回root或None.然后使用分治法, 如果左右节点的lowestCommonAnc...

闲庭信步 583

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

【Python Leetcode】236. Lowest Common Ancestor of a Binary Tree

python leetcode 236 LCA的解法

jessie_31655616的博客 625

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

[Java]Leetcode236 Lowest Common Ancestor of a Binary Tree

求二叉树的公共父结点

fumier的专栏 1455

[leetcode 236]Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two node

ER_Plough的专栏 720

LeetCode 236. Lowest Common Ancestor of a Binary Tree 详细题解

一:题意 给定一颗二叉树,两个节点p和q,求出节点p和节点q的最低公共祖先。 最先公共祖先的定义是:The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to...

rainMan的博客 260

[LeetCode] 236. Lowest Common Ancestor of a Binary Tree

题目: Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between

Allen的专栏 511

Leetcode236. Lowest Common Ancestor of a Binary Tree

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

magic_jiayu的博客 196

LeetCode 236 Lowest Common Ancestor of a Binary Tree

题目描述Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v

Yano_nankai的博客 627

leetcode-236-Lowest Common Ancestor of a Binary Tree

问题题目:[leetcode-236]思路公共祖先,想法和前一道题目最初的做法一样。 找到他们两的路径,然后比较路径的最浅公共节点。当然,有主意特殊数据的情形。 如果p和q在不在树里,显然没有公共父亲。 所以,虽然实际题意没有考虑这种情形,但是我应该考虑。然后,在判断是否存在root==p || root==q这种情形,因为不用再比了。 肯定是公共节点了。这个题有点烦的是getPath的实现

Kang_TJU的博客 419

LeetCode: 236. Lowest Common Ancestor of a Binary Tree

LeetCode: 236. Lowest Common Ancestor of a Binary Tree 题目描述 Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: ...

杨领well的专栏 147

LeetCode 236. Lowest Common Ancestor of a Binary Tree

LeetCode 236. Lowest Common Ancestor of a Binary Tree Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.According to the definition of LCA on Wikipedia:

两鬓已不能斑白的专栏 1325
上一篇: Leetcode 523. Continuous Subarray Sum
下一篇: Leetcode 239. Sliding Window Maximum
vincentCheungM
博客等级 码龄10年 4粉丝 23原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值