当前位置:网站首页>Minimum common ancestor of binary tree
Minimum common ancestor of binary tree
2022-06-11 02:57:00 【ambition_ forever】
public class Main {
private static TreeNode<Integer> ans;
private static boolean dfs(TreeNode<Integer> root, TreeNode<Integer> p, TreeNode<Integer> q) {
if (root == null) {
return false;
}
boolean lson = dfs(root.left, p, q);
boolean rson = dfs(root.right, p, q);
if ((lson && rson) || ((root.val.equals(p.val) || root.val.equals(q.val)) && (lson || rson))) {
ans = root;
}
return lson || rson || (root.val.equals(p.val) || root.val.equals(q.val));
}
public static TreeNode<Integer> lowestCommonAncestor(TreeNode<Integer> root, TreeNode<Integer> p, TreeNode<Integer> q) {
dfs(root, p, q);
return ans;
}
public static void main(String[] args) {
TreeNode<Integer> root = new TreeNode<Integer>(2);
root.left = new TreeNode<>(1);
root.right = new TreeNode<>(3);
System.out.println(lowestCommonAncestor(root, root.left, root.right).val);
}
}
边栏推荐
- Learning Tai Chi Maker - esp8226 (II)
- AOSP ~ modify WebView default implementation
- 求MySQL先按大于等于当前时间升序排序,再按小于当前时间降序排序
- OpenJudge NOI 1.13 18:Tomorrow never knows?
- Android P SoftAP start process
- CPT 102_ LEC 20
- The two departments jointly issued the nine provisions on fire safety management of off campus training institutions
- 出栈序列是否是入栈序列
- The Google search console webmaster tool cannot read the sitemap?
- 微信小程序
猜你喜欢

Go语言之Go 快速入门篇(一):第一个 Go 程序

牛客网:数组中只出现一次的两个数字

helm 部署traefik ingress

CPT 102_LEC 15

AOSP ~ 修改WebView默认实现

Graphacademy course explanation: Fundamentals of neo4j graph data science

逃离大城市的年轻人:扛住了房价和压力,没扛住流行病
![[long time series prediction] aotoformer code detailed [3] model overall architecture analysis](/img/77/30215c363ae8a1324db1cbcaa5324b.png)
[long time series prediction] aotoformer code detailed [3] model overall architecture analysis

CPT 102_ LEC 17

Istio安装与使用
随机推荐
Niuke: two numbers that only appear once in the array
Wechat template message errCode ": 40165," errmsg ":" invalid web pagepath
App test_ Summary of test points
Istio installation and use
那些笑着离开“北上广”的人,为何最后都哭了?
Prophet
How can Delma's own brand "take off" when Philips is listed on the market?
Databinding escaping with presentation symbols
Baidu submits sitemap to prompt the solution of "index type is not handled"
WordPress upgrade error: briefly unavailable for scheduled maintenance [resolved]
码农的进阶之路 | 每日趣闻
AOSP ~ 默认开启开发者模式
Question bank and answers for 2022 melting welding and thermal cutting operation certificate examination
Three special data types, day3 and redis (geographic location, cardinality statistics and bitmap scene usage)
When the interviewer opens his mouth, he comes to compose. Is this the case now?
Problems with JDBC tool classes
13. numeric array
剑指 Offer II 079. 所有子集
AOSP ~ modify default volume
数组全全排列