当前位置:网站首页>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);
}
}
边栏推荐
- Session
- About IPSec
- In the small skin panel, use CMD to enter the MySQL command, including the MySQL error unknown variable 'secure_ file_ Priv 'solution (super detailed)
- ACL 2022 | small sample ner of sequence annotation: dual tower Bert model integrating tag semantics
- SQL lab 21~25 summary (subsequent continuous update) (including secondary injection explanation)
- 静态Vxlan 配置
- 图像像素读写操作
- 详解ThinkPHP支持的URL模式有四种普通模式、PATHINFO、REWRITE和兼容模式
- 密码学系列之:在线证书状态协议OCSP详解
- 对话PPIO联合创始人王闻宇:整合边缘算力资源,开拓更多音视频服务场景
猜你喜欢
Preorder, inorder and postorder traversal of binary tree
Four functions of opencv
Day-18 hash table, generic
The left-hand side of an assignment expression may not be an optional property access.ts(2779)
浅谈估值模型 (二): PE指标II——PE Band
Importance of database security
静态Vxlan 配置
Vxlan 静态集中网关
Experiment with a web server that configures its own content
基于NeRF的三维内容生成
随机推荐
Zhimei creative website exercise
Static vxlan configuration
Polymorphism, final, etc
JS to convert array to tree data
【统计学习方法】学习笔记——第五章:决策树
layer弹出层的关闭问题
leetcode刷题:二叉树26(二叉搜索树中的插入操作)
Visual stdio 2017 about the environment configuration of opencv4.1
Realize all, race, allsettled and any of the simple version of promise by yourself
2022-07-07日报:GAN发明者Ian Goodfellow正式加入DeepMind
Day-17 connection set
@Resource和@Autowired的区别?
RHSA first day operation
[statistical learning methods] learning notes - Chapter 5: Decision Tree
Simple implementation of call, bind and apply
"Series after reading" my God! It's so simple to understand throttling and anti shake~
[statistical learning method] learning notes - support vector machine (I)
有什么类方法或是函数可以查看某个项目的Laravel版本的?
3D content generation based on nerf
ICLR 2022 | 基于对抗自注意力机制的预训练语言模型