当前位置:网站首页>Finding the nearest common ancestor of binary tree by recursion
Finding the nearest common ancestor of binary tree by recursion
2022-07-06 00:51:00 【Hydrion-Qlz】
236. The nearest common ancestor of a binary tree
difficulty : secondary
Given a binary tree , Find the nearest common ancestor of the two specified nodes in the tree .
Baidu Encyclopedia The definition of the most recent common ancestor in 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 ).
Ideas
If you can't understand this question, you can have a look first Find the nearest common ancestor of binary search tree
There are three situations
- Both nodes are smaller than the current node , Are all on the left subtree of the current node
- Both nodes are larger than the current node , Are all on the right subtree of the current node
- One is larger than the current node ( be equal to ), One is smaller than the current node ( be equal to ), Then the current node is the nearest common ancestor of the two nodes
But if it is implemented, we cannot judge whether it is on the left or right of the current node according to the value of the current node
So we can only traverse all subtrees of the current node , See if you can find at least one node on its left or right
- If the current node is equal to one of the nodes , Then return directly
- If there is a node on the left side and a node on the right side , It means that the current node is the nearest public child node
- If both are on one side , Then the nearest one must be at a node on that side
package cn.edu.xjtu.carlWay.tree.commonAncestor;
import cn.edu.xjtu.Util.TreeNode.TreeNode;
/** * 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 . * <p> * 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 ).” * <p> * https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/ */
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
// The node and its subtree must contain at least one node
if (root.val == p.val || root.val == q.val) {
return root;
}
// Judge whether the left and right subtrees of the current node contain at least one node
TreeNode leftNode = lowestCommonAncestor(root.left, p, q);
TreeNode rightNode = lowestCommonAncestor(root.right, p, q);
if (leftNode != null && rightNode != null) {
// If both the left subtree and the right subtree contain a node , It means that the current node is the nearest public child node
return root;
} else {
// Otherwise, the two must not do null The other side of the
return leftNode == null ? rightNode : leftNode;
}
}
}
边栏推荐
- Leetcode 450 deleting nodes in a binary search tree
- 小程序容器可以发挥的价值
- cf:D. Insert a Progression【关于数组中的插入 + 绝对值的性质 + 贪心一头一尾最值】
- Logstash clear sincedb_ Path upload records and retransmit log data
- 关于#数据库#的问题:(5)查询库存表中每本书的条码、位置和借阅的读者编号
- 95后CV工程师晒出工资单,狠补了这个,真香...
- Anconda download + add Tsinghua +tensorflow installation +no module named 'tensorflow' +kernelrestart: restart failed, kernel restart failed
- 图解网络:TCP三次握手背后的原理,为啥两次握手不可以?
- Spark DF adds a column
- Exciting, 2022 open atom global open source summit registration is hot
猜你喜欢
After Luke zettlemoyer, head of meta AI Seattle research | trillion parameters, will the large model continue to grow?
[groovy] compile time metaprogramming (compile time method injection | method injection using buildfromspec, buildfromstring, buildfromcode)
Common API classes and exception systems
可恢复保险丝特性测试
BiShe - College Student Association Management System Based on SSM
cf:D. Insert a Progression【关于数组中的插入 + 绝对值的性质 + 贪心一头一尾最值】
关于#数据库#的问题:(5)查询库存表中每本书的条码、位置和借阅的读者编号
MIT博士论文 | 使用神经符号学习的鲁棒可靠智能系统
Installation and use of esxi
After 95, the CV engineer posted the payroll and made up this. It's really fragrant
随机推荐
Starting from 1.5, build a micro Service Framework - call chain tracking traceid
XML Configuration File
Novice entry depth learning | 3-6: optimizer optimizers
Questions about database: (5) query the barcode, location and reader number of each book in the inventory table
How spark gets columns in dataframe --column, $, column, apply
Common API classes and exception systems
Analysis of the combination of small program technology advantages and industrial Internet
Overview of Zhuhai purification laboratory construction details
cf:C. The Third Problem【关于排列这件事】
Keepalive component cache does not take effect
An understanding of & array names
The value of applet containers
Curlpost PHP
VSphere implements virtual machine migration
关于#数据库#的问题:(5)查询库存表中每本书的条码、位置和借阅的读者编号
《强化学习周刊》第52期:Depth-CUPRL、DistSPECTRL & Double Deep Q-Network
NLP basic task word segmentation third party Library: ICTCLAS [the third party library with the highest accuracy of Chinese word segmentation] [Chinese Academy of Sciences] [charge]
The population logic of the request to read product data on the sap Spartacus home page
Pointer pointer array, array pointer
[simple implementation of file IO]