当前位置:网站首页>leetcode刷题:二叉树24(二叉树的最近公共祖先)
leetcode刷题:二叉树24(二叉树的最近公共祖先)
2022-07-07 10:30:00 【涛涛英语学不进去】
236. 二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]

示例 1:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
示例 2:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
说明:
- 所有节点的值都是唯一的。
- p、q 为不同节点且均存在于给定的二叉树中。
这题乍一看其实不难,就是找到这两个结点的路径,然后比较路径的上的值,找到最后一个相等的结点。
递归遍历,如果两个结点都找到,则停止递归。注意递归时要判断是不是单分支结点,不能用叶子结点为null作为终止条件,否则连删两次走过的路径,就结点缺失了,路径跳结点了。要判断,最后一个个删重复路径。
最后就是遍历的时候,这个卡我好久,可能是刷题刷迷糊了,类似 3 5 和 3 5 4 2 这样,找到最后一个公共元素,我做了半小时,无语,用指针法。
不能做了,停一停,散散步去。
package com.programmercarl.tree;
import com.programmercarl.util.GenerateTreeNode;
import java.util.*;
/** * @ClassName LowestCommonAncestor * @Descriotion TODO * @Author nitaotao * @Date 2022/7/6 10:12 * @Version 1.0 * https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/ * 236. 二叉树的最近公共祖先 **/
public class LowestCommonAncestor {
/** * 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 * 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x, * 满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” * 来源:力扣(LeetCode) * 链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @param root * @param p * @param q * @return */
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
/** * 思路清晰: * 找到两个结点的路径 * 路径值比较,当值不相等了,返回上一个路径值 */
this.p = p;
this.q = q;
traversal(root);
int size = Math.min(pPathNode.size(), qPathNode.size());
//指向公共元素
TreeNode result = pPathNode.get(0);
for (int i = 1; i < size; i++) {
if (pPathNode.get(i).val == qPathNode.get(i).val) {
result = pPathNode.get(i);
}
}
// pPathNode.stream().forEach((item) -> System.out.print(item.val));
// System.out.println();
// qPathNode.stream().forEach((item) -> System.out.print(item.val));
// System.out.println();
return result;
}
boolean isFindPandQ = false;
TreeNode p;
TreeNode q;
List<TreeNode> pPathNode = new ArrayList<TreeNode>();
List<TreeNode> qPathNode = new ArrayList<TreeNode>();
List<TreeNode> curPathNode = new ArrayList();
public void traversal(TreeNode root) {
if (isFindPandQ) {
//发现完毕,停止递归
return;
}
curPathNode.add(root);
if (root.val == p.val) {
pPathNode = new ArrayList<>(curPathNode);
//当两个都找到时停止递归
isFindPandQ = pPathNode.size() > 0 && qPathNode.size() > 0;
}
if (root.val == q.val) {
qPathNode = new ArrayList<>(curPathNode);
//当两个都找到时停止递归
isFindPandQ = pPathNode.size() > 0 && qPathNode.size() > 0;
}
//分开讨论两种情况,防止叶子结点删除两次最后位置
if (root.left != null) {
traversal(root.left);
}
if (root.right != null) {
traversal(root.right);
}
curPathNode.remove(curPathNode.size() - 1);
}
public static void main(String[] args) {
System.out.println(new LowestCommonAncestor().lowestCommonAncestor(GenerateTreeNode.generateTreeNode("[3,5,1,6,2,0,8,null,null,7,4]"), new TreeNode(5), new TreeNode(4)).val);
System.out.println(new LowestCommonAncestor().lowestCommonAncestor(GenerateTreeNode.generateTreeNode("[3,5,1,6,2,0,8,null,null,7,4]"), new TreeNode(5), new TreeNode(1)).val);
}
}

边栏推荐
- Processing strategy of message queue message loss and repeated message sending
- 利用棧來實現二進制轉化為十進制
- ps链接图层的使用方法和快捷键,ps图层链接怎么做的
- 【统计学习方法】学习笔记——提升方法
- EPP+DIS学习之路(2)——Blink!闪烁!
- SQL injection -- Audit of PHP source code (take SQL lab 1~15 as an example) (super detailed)
- ENSP MPLS layer 3 dedicated line
- SQL Lab (41~45) (continuous update later)
- About web content security policy directive some test cases specified through meta elements
- What is an esp/msr partition and how to create an esp/msr partition
猜你喜欢

MPLS experiment

Inverted index of ES underlying principle

SQL lab 26~31 summary (subsequent continuous update) (including parameter pollution explanation)
![[deep learning] image multi label classification task, Baidu paddleclas](/img/dd/6f213a396e8bb240a6872e4c03afab.png)
[deep learning] image multi label classification task, Baidu paddleclas

Simple network configuration for equipment management

SQL lab 11~20 summary (subsequent continuous update) contains the solution that Firefox can't catch local packages after 18 levels

AirServer自动接收多画面投屏或者跨设备投屏

<No. 9> 1805. Number of different integers in the string (simple)

SQL Lab (36~40) includes stack injection, MySQL_ real_ escape_ The difference between string and addslashes (continuous update after)

idm服务器响应显示您没有权限下载解决教程
随机推荐
(to be deleted later) yyds, paid academic resources, please keep a low profile!
【统计学习方法】学习笔记——支持向量机(上)
sql-lab (54-65)
Static comprehensive experiment
Airserver automatically receives multi screen projection or cross device projection
【PyTorch实战】用PyTorch实现基于神经网络的图像风格迁移
File upload vulnerability - upload labs (1~2)
When OSPF specifies that the connection type is P2P, it enables devices on both ends that are not in the same subnet to Ping each other
Sign up now | oar hacker marathon phase III midsummer debut, waiting for you to challenge
An error occurred when vscade tried to create a file in the target directory: access denied [resolved]
对话PPIO联合创始人王闻宇:整合边缘算力资源,开拓更多音视频服务场景
ps链接图层的使用方法和快捷键,ps图层链接怎么做的
Tutorial on principles and applications of database system (009) -- conceptual model and data model
Routing strategy of multi-point republication [Huawei]
Unity map auto match material tool map auto add to shader tool shader match map tool map made by substance painter auto match shader tool
[Q&A]AttributeError: module ‘signal‘ has no attribute ‘SIGALRM‘
2022 8th "certification Cup" China University risk management and control ability challenge
Simple network configuration for equipment management
数据库系统原理与应用教程(007)—— 数据库相关概念
MPLS experiment