当前位置: 首页 > news >正文

LeetCode236. 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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Example 3:

Input: root = [1,2], p = 1, q = 2
Output: 1

Constraints:

The number of nodes in the tree is in the range [2, 105].
-109 <= Node.val <= 109
All Node.val are unique.
p != q
p and q will exist in the tree.

二、题解

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if(!root) return NULL;if(root->val == p->val || root->val == q->val) return root;TreeNode* left = lowestCommonAncestor(root->left,p,q);TreeNode* right = lowestCommonAncestor(root->right,p,q);if(left != NULL && right != NULL) return root;else if(left == NULL && right != NULL) return right;else if(left != NULL && right == NULL) return left;else return NULL;}
};
http://www.lryc.cn/news/234175.html

相关文章:

  • 基于Gin+Gorm框架搭建MVC模式的Go语言企业级后端系统
  • 【开源】基于Vue和SpringBoot的固始鹅块销售系统
  • Windows11怎样投屏到电视上?
  • ubuntu中用docker部署jenkins,并和码云实现自动化部署
  • for,while,do-while,死循环,嵌套循环,跳转关键字,随机数
  • 【六袆 - MySQL】SQL优化;Explain SQL执行计划分析;
  • 【AI视野·今日NLP 自然语言处理论文速览 第六十二期】Wed, 25 Oct 2023
  • 各种符号地址,可以直接复制粘贴使用
  • C语言测试题:用冒泡法对输入的10个字符由小到大排序 ,要求数组做为函数参数。
  • uni-app开发微信小程序 vue3写法添加pinia
  • centos三台主机配置互信ssh登录
  • 验证码案例 —— Kaptcha 插件介绍 后端生成验证码,前端展示并进行session验证(带完整前后端源码)
  • js/jQuery 的一些常用操作(js/jQuery获取表单元素值 以及 清空元素值的各种实现方式)——附测试例子,拿来即能实现效果
  • h5(react ts 适配)
  • 计算机视觉:驾驶员疲劳检测
  • Vue向pdf文件中添加二维码
  • idea一键打包docker镜像并推送远程harbor仓库的方法(包含spotify和fabric8两种方法)--全网唯一正确,秒杀99%水文
  • 程序设计:C++11原子 写优先的读写锁(源码详解二:操作跟踪)
  • Django视图层解析
  • JAVA使用RXTXcomm进行串口通信(一)
  • Vue+ElementUI技巧分享:自定义表单项label的文字提示
  • 【QML】警告Name is declared more than once
  • 【自用总结】正项级数审敛法的总结
  • ARMv8平台上安装QT开发环境
  • 基于人工电场算法优化概率神经网络PNN的分类预测 - 附代码
  • 在服务器导出kafka topic数据
  • 农户建档管理系统的设计与实现-计算机毕业设计源码20835
  • uniapp的Vue2,Vue3配置跨域(proxy代理)
  • 处理BOP数据集,将其和COCO数据集结合
  • 跟李沐学AI-深度学习课程05线性代数