当前位置:网站首页>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)
边栏推荐
- How can Oracle CDC deserialize with jsondebeziumdeserializationschema
- 求帮助xampp做sqlilab是一片黑
- 这个『根据 op 值判断操作类型来自己组装 sql』是指在哪里实现?是指单纯用 Flink Tabl
- flinksql select id ,count(*) from a group by id .
- Dockermysql modifies the root account password and grants permissions
- Can async i/o be implemented by UDF operator and then called by SQL API? At present, it seems that only datastre can be seen
- B站大佬用我的世界搞出卷積神經網絡,LeCun轉發!爆肝6個月,播放破百萬
- 云原生(三十二) | Kubernetes篇之平台存储系统介绍
- asp读取oracle数据库问题
- flinksql select id ,count(*) from a group by id .
猜你喜欢
Docker starts MySQL and -emysql_ ROOT_ Password = my secret PW problem solving
[launched in the whole network] redis series 3: high availability of master-slave architecture
Gold three silver four, don't change jobs
If the request URL contains jsessionid, the solution
Today, I met a senior test developer from Tencent and saw the ceiling of the foundation
The best sister won the big factory offer of 8 test posts at one go, which made me very proud
公链与私链在数据隐私和吞吐量上的竞争
Isomorphism + cross end, knowing applet +kbone+finclip is enough!
Master binary tree in one article
After 3 years of testing bytecan software, I was ruthlessly dismissed in February, trying to wake up my brother who was paddling
随机推荐
Can online reload system software be used safely? Test use experience to share with you
机器人材料整理中的套-假-大-空话
每人每年最高500万经费!选人不选项目,专注基础科研,科学家主导腾讯出资的「新基石」启动申报...
浅谈现在的弊端与未来的发展
Docker mysql5.7 how to set case insensitive
JS addition, deletion, modification and query of JSON array
AI表现越差,获得奖金越高?纽约大学博士拿出百万重金,悬赏让大模型表现差劲的任务...
自动更新Selenium驱动chromedriver
The same job has two sources, and the same link has different database accounts. Why is the database list found in the second link the first account
Per capita Swiss number series, Swiss number 4 generation JS reverse analysis
docker中mysql开启日志的实现步骤
Huawei cloud gaussdb (for redis) unveils issue 21: using Gauss redis to achieve secondary indexing
What does front-end processor mean? What is the main function? What is the difference with fortress machine?
Precise drag and drop within a contentable
求帮助xampp做sqlilab是一片黑
Gold three silver four, don't change jobs
Use mitmproxy to cache 360 degree panoramic web pages offline
What does security capability mean? What are the protection capabilities of different levels of ISO?
Isomorphism + cross end, knowing applet +kbone+finclip is enough!
(1) Chang'an chain learning notes - start Chang'an chain