当前位置:网站首页>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;
}
}
}
边栏推荐
- Programmer growth Chapter 9: precautions in real projects
- Spark SQL null value, Nan judgment and processing
- Keepalive component cache does not take effect
- 程序员成长第九篇:真实项目中的注意事项
- After Luke zettlemoyer, head of meta AI Seattle research | trillion parameters, will the large model continue to grow?
- I'm interested in watching Tiktok live beyond concert
- MobileNet系列(5):使用pytorch搭建MobileNetV3并基于迁移学习训练
- NLP generation model 2017: Why are those in transformer
- Uniapp development, packaged as H5 and deployed to the server
- Hundreds of lines of code to implement a JSON parser
猜你喜欢

XML配置文件
![[groovy] JSON serialization (convert class objects to JSON strings | convert using jsonbuilder | convert using jsonoutput | format JSON strings for output)](/img/52/021931181ad3f4bef271b4e98105c2.jpg)
[groovy] JSON serialization (convert class objects to JSON strings | convert using jsonbuilder | convert using jsonoutput | format JSON strings for output)

Illustrated network: the principle behind TCP three-time handshake, why can't two-time handshake?

Recoverable fuse characteristic test

After 95, the CV engineer posted the payroll and made up this. It's really fragrant

Intensive learning weekly, issue 52: depth cuprl, distspectrl & double deep q-network

免费的聊天机器人API
![[groovy] compile time meta programming (AST syntax tree conversion with annotations | define annotations and use groovyasttransformationclass to indicate ast conversion interface | ast conversion inte](/img/61/73becfc3b46669d31b0cf334aa54f2.jpg)
[groovy] compile time meta programming (AST syntax tree conversion with annotations | define annotations and use groovyasttransformationclass to indicate ast conversion interface | ast conversion inte

cf:C. The Third Problem【关于排列这件事】

Questions about database: (5) query the barcode, location and reader number of each book in the inventory table
随机推荐
Spark DF增加一列
Problems and solutions of converting date into specified string in date class
Ffmpeg captures RTSP images for image analysis
如何制作自己的机器人
Questions about database: (5) query the barcode, location and reader number of each book in the inventory table
STM32按键消抖——入门状态机思维
Analysis of the combination of small program technology advantages and industrial Internet
The relationship between FPGA internal hardware structure and code
Study diary: February 13, 2022
Basic introduction and source code analysis of webrtc threads
Leetcode:20220213 week race (less bugs, top 10% 555)
Dynamic programming -- linear DP
Kotlin core programming - algebraic data types and pattern matching (3)
《强化学习周刊》第52期:Depth-CUPRL、DistSPECTRL & Double Deep Q-Network
Cloud guide DNS, knowledge popularization and classroom notes
Ubantu check cudnn and CUDA versions
Starting from 1.5, build a micro Service Framework - call chain tracking traceid
Cannot resolve symbol error
VSphere implements virtual machine migration
What is the most suitable book for programmers to engage in open source?