当前位置:网站首页>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)
边栏推荐
- mysql查看表结构的三种方法总结
- 【OFDM通信】基于深度学习的OFDM系统信号检测附matlab代码
- CRMEB 商城系统如何助力营销?
- 自动更新Selenium驱动chromedriver
- 不要再说微服务可以解决一切问题了
- 同构+跨端,懂得小程序+kbone+finclip就够了!
- I've been laid off, and I'll lose money for everything. The days when I once made a monthly salary of 20000 are not coming back
- Flutter life cycle
- 云原生(三十二) | Kubernetes篇之平台存储系统介绍
- GPT-3当一作自己研究自己,已投稿,在线蹲一个同行评议
猜你喜欢

None of the strongest kings in the monitoring industry!

Entropy information entropy cross entropy

Gpt-3 is a peer review online when it has been submitted for its own research

Ajout, suppression et modification d'un tableau json par JS

JDBC programming of MySQL database

Efficient ETL Testing

Why are some people still poor and living at the bottom of society even though they have been working hard?
The problem that dockermysql cannot be accessed by the host machine is solved

若依请求url中带有jsessionid的解决办法

Modules that can be used by both the electron main process and the rendering process
随机推荐
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.
Children's pajamas (Australia) as/nzs 1249:2014 handling process
One minute to learn how to install the system, win7 XP, win10 and win11 become very simple
Huawei cloud gaussdb (for redis) unveils issue 21: using Gauss redis to achieve secondary indexing
MySQL数据库之JDBC编程
Pytest unit test series [v1.0.0] [pytest execute unittest test case]
JDBC programming of MySQL database
How can Oracle CDC deserialize with jsondebeziumdeserializationschema
Ajout, suppression et modification d'un tableau json par JS
AcWing 4299. Delete point
leetcode:236. 二叉树的最近公共祖先
What does security capability mean? What are the protection capabilities of different levels of ISO?
资产安全问题或制约加密行业发展 风控+合规成为平台破局关键
Up to 5million per person per year! Choose people instead of projects, focus on basic scientific research, and scientists dominate the "new cornerstone" funded by Tencent to start the application
短链的设计
Gradle知识概括
Laravel8 uses passport authentication to log in and generate a token
Hard core observation 545 50 years ago, Apollo 15 made a feather landing experiment on the moon
I've been laid off, and I'll lose money for everything. The days when I once made a monthly salary of 20000 are not coming back
Where does this "judge the operation type according to the op value and assemble SQL by yourself" mean? It means simply using Flink tab