当前位置:网站首页>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);
}
}
边栏推荐
- [interview question 17.04. missing numbers]
- Recent learning and update plan
- Uni app - one click access to user information
- CPT 102_LEC 13-14
- Three special data types, day3 and redis (geographic location, cardinality statistics and bitmap scene usage)
- CPT 102_LEC 15
- How to add cookie pop-up window in WordPress website (without plug-in)
- 基于互联网架构演进, 构建秒杀系统
- Net core Tianma XingKong series - Interface Implementation for dependency injection and mutual conversion of database tables and C entity classes
- The Google search console webmaster tool cannot read the sitemap?
猜你喜欢

新来的同事问我 where 1=1 是什么意思???

【冒泡排序的实现】

Write my Ini configuration file error

Wechat applet

Common vocabulary of software testing English

码农的进阶之路 | 每日趣闻

CocosCreator原生二次开发的正确姿势

One line of code solves the problem that the time to fetch datetime from MySQL database is less than eight hours

How to add cookie pop-up window in WordPress website (without plug-in)

Necessity for banks to choose electronic bidding procurement
随机推荐
OpenJudge NOI 1.13 18:Tomorrow never knows?
What is ttfb
js 内存泄漏
弄懂了采矿业与碳中和的逻辑,就读懂了矿区无人驾驶的千亿市场
Introduction to the functions of today's headline search webmaster platform (portal)
Why did those who left Beijing, Shanghai and Guangzhou with a smile cry in the end?
Helm deploy traifik ingress
20220610 星期五
银行选择电子招标采购的必要性
HUST软件工程(实验2)--TDD测试驱动开发实验。
AOSP ~ modify WebView default implementation
Error excluded identifier before '(' token, grpc enumeration class compilation error
How to use phpMyAdmin to optimize MySQL database
Rs232/rs485 to 4G DTU uploading temperature and humidity sensor data based on Modbus protocol to remote TCP server
Android WiFi hide SSID configuration method
The new colleague asked me what "where 1=1" means???
CPT 102_LEC 18
Arduino Uno接JQ8900-16p语音播报模块
[interview question 17.04. missing numbers]
The two departments jointly issued the nine provisions on fire safety management of off campus training institutions