当前位置:网站首页>236. The nearest common ancestor of a binary tree
236. The nearest common ancestor of a binary tree
2022-07-26 17:52:00 【Sugar loving Xu CAI】
List of articles
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 .
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 ).”
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, 105]Inside . -109 <= Node.val <= 109- all
Node.valDifferent from each other. p != qpandqAll exist in a given binary tree .
Ideas :
function lowestCommonAncestor The return value of is node p and q The latest public ancestor of , It's easy to think of , From bottom to top , Check each node in turn , Is it a node p and q The latest public ancestor of .
Need to meet the conditions :
- p and q stay root On both sides of
- perhaps q perhaps p be equal to root, Another node is root In the subtree
Deep understanding of functions lowestCommonAncestor The return value of :
- If not in the tree p And there's no q, Just go back to
NULL - If there is only p Or just q, Just go back to p perhaps q
- Yes p And there are q, Return to the nearest common ancestor
Arrangement :
Combined with the above ideas , You can think of , Using recursion , Until I find p and q, Then in the recursive backtracking process , Solve the problem . Refer to the idea of code Capriccio :
- Determine the return value and parameters of the recursive function
The meaning of the return value is : node p and q The latest public ancestor of
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
Determine termination conditions
If not in the tree p And there's no q, Just go back to
NULLIf there is only p Or just q, Just go back to p perhaps q
if (!root) return NULL; if (root == q || root == p) return root;
- Recursive logic
- If left and right All have non empty return values , explain root It's the latest public ancestor
- If one is empty , Then the non empty one is root For the tree of the root node
lowestCommonAncestorFunction return value - If it's all empty , be NULL In order to root For the tree of the root node
lowestCommonAncestorFunction return value
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
Code :
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return NULL;
if (root == q || root == p) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right)
return root;
else if (!left)
return right;
else
return left;
}
};
summary :
Although this is a simple question , But I understand for a long time , Write an explanation and take notes .
边栏推荐
- [training Day1] Dwaves line up
- JS 函数作用域 变量声明提升 作用域链 不加var的变量,是全局变量
- Application of machine vision in service robot
- How to use align regexp to align userscript meta information
- Is it safe for Changzheng securities to open an account?
- 基本的SELECT语句
- [training Day1] spy dispatch
- Mondriaans's dream (state compression DP)
- [300 opencv routines] 240. Shi Tomas corner detection in opencv
- Analysis of interface testing
猜你喜欢

Definition of graph traversal and depth first search and breadth first search (I)

【集训Day2】Torchbearer
![[template] segment tree 1](/img/60/9f73d00223c8878ffd8513b3b9adf7.jpg)
[template] segment tree 1

leetcode:1206. 设计跳表【跳表板子】

Asemi rectifier bridge kbpc3510, kbpc3510 package, kbpc3510 application

如何组装一个注册中心?

带你熟悉云网络的“电话簿”:DNS

Come on developer! Not only for the 200000 bonus, try the best "building blocks" for a brainstorming

【集训Day1】 Dwarves line up

Interview with celebrities | open source is a double-edged sword for security -- Wei Jianfan, author of the Chinese translation of cathedral and market
随机推荐
Performance tuning bugs emerge in endlessly? These three documents can easily handle JVM tuning
Leetcode:1206. design jump table [jump table board]
Is it safe to open an account online now? Who do you want to open a stock account?
Brief introduction to CUDA image construction
图的遍历的定义以及深度优先搜索和广度优先搜索(一)
点击劫持攻击
【虚拟机数据恢复】意外断电导致XenServer虚拟机不可用,虚拟磁盘文件丢失的数据恢复案例
硬件开发与市场产业
(25)Blender源码分析之顶层菜单Blender菜单
PIP installation module, error
Spark data format unsafe row
the loss outweighs the gain! Doctors cheated 2.1 million yuan and masters cheated 30000 yuan of talent subsidies, all of which were sentenced!
ACL experiment demonstration (Huawei router device configuration)
Cloud rendering volume cloud [theoretical basis and implementation scheme]
JS closure simulates private variable interview questions and immediately executes function Iife
Tianyi cloud web application firewall (edge cloud version) supports the detection and interception of Apache spark shell command injection vulnerabilities
徽商期货网上开户安全吗?开户办理流程是怎样的?
就这一次!详细聊聊分布式系统的那些技术方案
2.1.2 synchronization always fails
Tree DP problem