当前位置:网站首页>Leetcode brush question: binary tree 24 (the nearest common ancestor of binary tree)
Leetcode brush question: binary tree 24 (the nearest common ancestor of binary tree)
2022-07-07 12:48:00 【Taotao can't learn English】
236. The nearest common ancestor of a binary tree
Given a binary tree , Find the nearest common ancestor of the two specified nodes in the tree .
In Baidu Encyclopedia, the most recent definition of public ancestor is :“ For a tree T Two nodes of p、q, Recently, the common ancestor is represented as a node x, Satisfy x yes p、q Our ancestors and x As deep as possible ( A node can also be its own ancestor ).”
for example , Given the following binary tree : root = [3,5,1,6,2,0,8,null,null,7,4]
Example 1:
Input : root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output : 3
explain : node 5 And nodes 1 The most recent public ancestor of is the node 3.
Example 2:
Input : root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output : 5
explain : node 5 And nodes 4 The most recent public ancestor of is the node 5. Because by definition, the nearest common ancestor node can be the node itself .
explain :
- The values of all nodes are unique .
- p、q For different nodes and all exist in a given binary tree .
At first glance, this problem is not difficult , Is to find the path of these two nodes , Then compare the values on the path , Find the last equal node .
Recursive traversal , If both nodes are found , Stop recursion . Pay attention to whether it is a single branch node when recursing , The leaf node cannot be null As a condition of termination , Otherwise, delete the path taken twice , The node is missing , The path jumps to the node . To judge , Delete the repeated paths one by one .
Finally, when traversing , I've had this card for a long time , Maybe I'm confused when I brush the questions , similar 3 5 and 3 5 4 2 such , Find the last common element , I did it for half an hour , speechless , Using pointer method .
Can't do , Stop. Stop , Take a walk .
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. The nearest common ancestor of a binary tree **/
public class LowestCommonAncestor {
/** * Given a binary tree , Find the nearest common ancestor of the two specified nodes in the tree . * In Baidu Encyclopedia, the most recent definition of public ancestor is :“ For a tree T Two nodes of p、q, The nearest common ancestor is represented as a node x, * Satisfy x yes p、q Our ancestors and x As deep as possible ( A node can also be its own ancestor ).” * source : Power button (LeetCode) * link :https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree * Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source . * * @param root * @param p * @param q * @return */
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
/** * have a lucid brain : * Find the path of two nodes * Path value comparison , When the values are not equal , Return the previous path value */
this.p = p;
this.q = q;
traversal(root);
int size = Math.min(pPathNode.size(), qPathNode.size());
// Point to common elements
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) {
// The discovery is complete , Stop recursion
return;
}
curPathNode.add(root);
if (root.val == p.val) {
pPathNode = new ArrayList<>(curPathNode);
// Stop recursion when both are found
isFindPandQ = pPathNode.size() > 0 && qPathNode.size() > 0;
}
if (root.val == q.val) {
qPathNode = new ArrayList<>(curPathNode);
// Stop recursion when both are found
isFindPandQ = pPathNode.size() > 0 && qPathNode.size() > 0;
}
// Discuss the two situations separately , Prevent the leaf node from deleting the last position twice
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);
}
}
边栏推荐
- leetcode刷题:二叉树25(二叉搜索树的最近公共祖先)
- 2022A特种设备相关管理(锅炉压力容器压力管道)模拟考试题库模拟考试平台操作
- Configure an encrypted web server
- Day-16 set
- 什么是ESP/MSR 分区,如何建立ESP/MSR 分区
- 聊聊Redis缓存4种集群方案、及优缺点对比
- Multi row and multi column flex layout
- AirServer自动接收多画面投屏或者跨设备投屏
- [difficult and miscellaneous]pip running suddenly appears modulenotfounderror: no module named 'pip‘
- Preorder, inorder and postorder traversal of binary tree
猜你喜欢
Airserver automatically receives multi screen projection or cross device projection
对话PPIO联合创始人王闻宇:整合边缘算力资源,开拓更多音视频服务场景
Day-15 common APIs and exception mechanisms
聊聊Redis缓存4种集群方案、及优缺点对比
In the small skin panel, use CMD to enter the MySQL command, including the MySQL error unknown variable 'secure_ file_ Priv 'solution (super detailed)
Pule frog small 5D movie equipment | 5D movie dynamic movie experience hall | VR scenic area cinema equipment
Zhimei creative website exercise
图像像素读写操作
Image pixel read / write operation
How to apply @transactional transaction annotation to perfection?
随机推荐
Realize a simple version of array by yourself from
About sqli lab less-15 using or instead of and parsing
Aike AI frontier promotion (7.7)
Pule frog small 5D movie equipment | 5D movie dynamic movie experience hall | VR scenic area cinema equipment
leetcode刷题:二叉树22(二叉搜索树的最小绝对差)
2022 practice questions and mock examination of the third batch of Guangdong Provincial Safety Officer a certificate (main person in charge)
用mysql查询某字段是否有索引
Utiliser la pile pour convertir le binaire en décimal
SQL Lab (36~40) includes stack injection, MySQL_ real_ escape_ The difference between string and addslashes (continuous update after)
ICLR 2022 | 基于对抗自注意力机制的预训练语言模型
SQL blind injection (WEB penetration)
聊聊Redis缓存4种集群方案、及优缺点对比
3D content generation based on nerf
visual stdio 2017关于opencv4.1的环境配置
[learn microservice from 0] [01] what is microservice
【PyTorch实战】用PyTorch实现基于神经网络的图像风格迁移
[爬虫]使用selenium时,躲避脚本检测
详解ThinkPHP支持的URL模式有四种普通模式、PATHINFO、REWRITE和兼容模式
leetcode刷题:二叉树23(二叉搜索树中的众数)
编译 libssl 报错