当前位置:网站首页>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);
}
}
边栏推荐
- 《看完就懂系列》天哪!搞懂节流与防抖竟简单如斯~
- 问题:先后键入字符串和字符,结果发生冲突
- Will the filing free server affect the ranking and weight of the website?
- 让数字管理好库存
- An error occurred when vscade tried to create a file in the target directory: access denied [resolved]
- 数据库系统原理与应用教程(009)—— 概念模型与数据模型
- Vxlan static centralized gateway
- wallys/Qualcomm IPQ8072A networking SBC supports dual 10GbE, WiFi 6
- 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
- SQL lab 11~20 summary (subsequent continuous update) contains the solution that Firefox can't catch local packages after 18 levels
猜你喜欢
Epp+dis learning road (2) -- blink! twinkle!
SQL head injection -- injection principle and essence
小红书微服务框架及治理等云原生业务架构演进案例
Idea 2021 Chinese garbled code
Static routing assignment of network reachable and telent connections
About web content security policy directive some test cases specified through meta elements
《看完就懂系列》天哪!搞懂节流与防抖竟简单如斯~
[play RT thread] RT thread Studio - key control motor forward and reverse rotation, buzzer
解决 Server returns invalid timezone. Go to ‘Advanced’ tab and set ‘serverTimezone’ property manually
Vxlan static centralized gateway
随机推荐
BGP actual network configuration
Vxlan 静态集中网关
ES底层原理之倒排索引
平安证券手机行开户安全吗?
Is it safe to open Huatai's account in kainiu in 2022?
H3C HCl MPLS layer 2 dedicated line experiment
【PyTorch实战】用PyTorch实现基于神经网络的图像风格迁移
Review and arrangement of HCIA
Static vxlan configuration
Solutions to cross domain problems
SQL lab 1~10 summary (subsequent continuous update)
Attack and defense world ----- summary of web knowledge points
消息队列消息丢失和消息重复发送的处理策略
解决 Server returns invalid timezone. Go to ‘Advanced’ tab and set ‘serverTimezone’ property manually
30. Feed shot named entity recognition with self describing networks reading notes
Tutorial on principles and applications of database system (009) -- conceptual model and data model
What are the top-level domain names? How is it classified?
SQL head injection -- injection principle and essence
Simple network configuration for equipment management
浅谈估值模型 (二): PE指标II——PE Band