当前位置:网站首页>leetcode:236. The nearest common ancestor of binary tree
leetcode:236. The nearest common ancestor of binary tree
2022-07-06 23:33:00 【uncle_ ll】
236. The nearest common ancestor of a binary tree
source : Power button (LeetCode)
link : https://leetcode.cn/problems/lowest-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, 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 ).”
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 .

Example 3:
Input :root = [1,2], p = 1, q = 2
Output :1
Tips :
- The number of nodes in the tree is in the range [2, 1 0 5 10^5 105] Inside .
- − 1 0 9 -10^9 −109 <= Node.val <= 1 0 9 10^9 109
- all Node.val Different from each other .
- p != q
- p and q All exist in a given binary tree .
solution
- recursive : Start with the root node , If the root node is empty , Or a search element is the root node , Directly back to the root node ; Then recursively find the left subtree , Right subtree , If the search results of both subtrees are not empty , indicate p,q The two elements to be found are the same as the root node of the left subtree or the root node of the right subtree , Then the common node of the two is the root node of the tree ; If the search of a subtree is empty , Then return the search result of another subtree ;
Code implementation
recursive
python Realization
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return root
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right: # The search results of the two subtrees are not empty , Description shot ,
return root
return left if left else right
c++ Realization
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr)
return root;
if (p == root || q == root)
return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != nullptr && right != nullptr)
return root;
return left != nullptr ? left : right;
}
};
Complexity analysis
- Time complexity : O ( N ) O(N) O(N)
- Spatial complexity : O ( N ) O(N) O(N)
边栏推荐
- 11 preparations for Web3 and Decentralization for traditional enterprises
- Without CD, I'll teach you a trick to restore the factory settings of win10 system
- Computer reinstallation system teaching, one click fool operation, 80% of people have learned
- After 3 years of testing bytecan software, I was ruthlessly dismissed in February, trying to wake up my brother who was paddling
- Efficient ETL Testing
- COSCon'22 社区召集令来啦!Open the World,邀请所有社区一起拥抱开源,打开新世界~
- Nftscan Developer Platform launches Pro API commercial services
- What does security capability mean? What are the protection capabilities of different levels of ISO?
- MySQL数据库之JDBC编程
- docker启动mysql及-eMYSQL_ROOT_PASSWORD=my-secret-pw问题解决
猜你喜欢

(shuttle) navigation return interception: willpopscope

人均瑞数系列,瑞数 4 代 JS 逆向分析

Station B Big utilise mon monde pour faire un réseau neuronal convolutif, Le Cun Forward! Le foie a explosé pendant 6 mois, et un million de fois.

资产安全问题或制约加密行业发展 风控+合规成为平台破局关键

B 站弹幕 protobuf 协议还原分析

The best sister won the big factory offer of 8 test posts at one go, which made me very proud

Koa2 addition, deletion, modification and query of JSON array

The important data in the computer was accidentally deleted by mistake, which can be quickly retrieved by this method
MySQL实现字段分割一行转多行的示例代码

Restoration analysis of protobuf protocol of bullet screen in station B
随机推荐
Use mitmproxy to cache 360 degree panoramic web pages offline
自动更新Selenium驱动chromedriver
After 3 years of testing bytecan software, I was ruthlessly dismissed in February, trying to wake up my brother who was paddling
ArrayExpress数据库里的细胞只有两个txt是不是只能根据Line到ENA下载测序跑矩阵?
The programmer said, "I'm 36 years old, and I don't want to be rolled, let alone cut."
(flutter2) as import old project error: inheritfromwidgetofexacttype
JDBC programming of MySQL database
Gradle知識概括
每日刷题记录 (十五)
Experiment 5: common automation libraries
Can online reload system software be used safely? Test use experience to share with you
Cover fake big empty talk in robot material sorting
Efficient ETL Testing
One minute to learn how to install the system, win7 XP, win10 and win11 become very simple
【通信】两层无线 Femtocell 网络上行链路中的最优功率分配附matlab代码
js导入excel&导出excel
Experiment 4: installing packages from Gui
What does security capability mean? What are the protection capabilities of different levels of ISO?
A few suggestions for making rust library more beautiful! Have you learned?
《数字经济全景白皮书》保险数字化篇 重磅发布