当前位置:网站首页>#yyds干货盘点# 解决剑指offer:在二叉树中找到两个节点的最近公共祖先
#yyds干货盘点# 解决剑指offer:在二叉树中找到两个节点的最近公共祖先
2022-06-29 12:36:00 【51CTO】
1.简述:
描述
给定一棵二叉树(保证非空)以及这棵树上的两个节点对应的val值 o1 和 o2,请找到 o1 和 o2 的最近公共祖先节点。数据范围:树上节点数满足 , 节点值val满足区间 [0,n)要求:时间复杂度
注:本题保证二叉树中每个节点的val值均不相同。如当输入{3,5,1,6,2,0,8,#,#,7,4},5,1时,二叉树{3,5,1,6,2,0,8,#,#,7,4}如下图所示:
所以节点值为5和节点值为1的节点的最近公共祖先节点的节点值为3,所以对应的输出为3。节点本身可以视为自己的祖先
示例1
输入:
返回值:
示例2
输入:
返回值:
2.代码实现:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
public int lowestCommonAncestor(TreeNode root, int o1, int o2) {
return helper(root, o1, o2).val;
}
public TreeNode helper(TreeNode root, int o1, int o2) {
if (root == null || root.val == o1 || root.val == o2)
return root;
TreeNode left = helper(root.left, o1, o2);
TreeNode right = helper(root.right, o1, o2);
//如果left为空,说明这两个节点在root结点的右子树上,我们只需要返回右子树查找的结果即可
if (left == null)
return right;
//同上
if (right == null)
return left;
//如果left和right都不为空,说明这两个节点一个在root的左子树上一个在root的右子树上,
//我们只需要返回cur结点即可。
return root;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
边栏推荐
- Design of commodity search engine recommendation system
- Uber前安全主管面临欺诈指控 曾隐瞒数据泄露事件
- Matlab to find the limit
- 趣谈网络协议(二)传输层
- Async principle implementation
- Netdata mail alarm configuration
- matplotlib的imshow函数显示灰度图像要设置vmin和vmax2个参数
- Principle and Simulation of bind
- Acwing 234 abandoning testing
- [cloud resident co creation] industrial wisdom "brain", a new acceleration script for old factories
猜你喜欢

Acwing 234 abandoning testing

CVPR2022 | 弱监督多标签分类中的损失问题

Cvpr2022 | a convnet for the 2020s & how to design neural network Summary

iMile 利用 Zadig 多云环境周部署千次,跨云跨地域持续交付全球业务

Precautions for Beifu controller connecting Panasonic EtherCAT servo

C language character function

Windbg常用命令详解

思科模拟器简单校园网设计,期末作业难度

win32版俄罗斯方块(学习MFC必不可少)

Cvpr2022 𞓜 future transformer with long-term action expectation
随机推荐
Cvpr2022 𞓜 loss problem in weakly supervised multi label classification
iMile 利用 Zadig 多云环境周部署千次,跨云跨地域持续交付全球业务
Qitai observation: professional elites must step on the huge pit of entrepreneurship - learning effect pit
C语言字符函数
编写一个shell脚本,求一个数的”逆序数“
CVPR 2022 | unknown target detection module study: learning unknown targets in video
netdata数据持久化配置
C语言模拟实现所有字符函数
Windwos10 installing sshd service
leetcode 903. DI 序列的有效排列
从零搭建Pytorch模型教程(四)编写训练过程--参数解析
趣谈网络协议(二)传输层
Windbg常用命令详解
强大、优秀的文件管理软件评测:图片管理、书籍管理、文献管理
Cvpr2022 𞓜 thin domain adaptation
The imshow function of Matplotlib displays grayscale images. Vmin and vmax2 parameters should be set
STK_ Gltf model
六月集训(第29天) —— 分而治之
CVPR 2022 | 未知目标检测模块STUD:学习视频中的未知目标
Tree array application (acwing 24224244)