当前位置:网站首页>Title: the nearest common ancestor of binary tree
Title: the nearest common ancestor of binary tree
2022-07-16 07:17:00 【Chenchen-】
// Explain 1
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// LCA problem
if (root == null) {
return root;
}
if (root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
} else if (left != null) {
return left;
} else if (right != null) {
return right;
}
return null;
}
// Explain 2
When binary tree The left node of the current node It must be smaller than the current node The right node must be larger than the current node Or vice versa , You can use the following algorithm
if(root.val==p.val||root.val==q.val){
return root;
}
if (root.val > p.val &&root.val > q.val) {
return lowestCommonAncestor( root.right, p, q);
}
if (root.val < p.val &&root.val < q.val) {
return lowestCommonAncestor( root.left, p, q);
}
return root;边栏推荐
- unity3d-Camera
- 单向链表实现队列和栈
- SAP ABAP BP batch maintenance email address
- Implementation of binarysearchtree (BST) class template for binary search tree
- SAP OPEN SQL
- SAP ABAP Smartforms 踩过的坑
- Leetcode lecture - 676 Implement a magic Dictionary (difficulty: medium)
- Unity3d common components
- redis基础知识——菜鸟教程
- Unity3d-小技巧
猜你喜欢

Small stage summary

Xiaomi held the 5th IOT security summit to help protect industry security and privacy

SAP DUMP CALLBACK_REJECTED_BY_WHITELIST - SE51, RSSCREENPAINTER

【6月5号学习记录】

线程机制与事件机制

LeetCode精讲——735. 行星碰撞(难度:中等)

类型擦除&桥接方法

Mysql - page de données

散列表HashTable线性探测法类模板的实现

LeetCode精讲——873. 最长的斐波那契子序列的长度(难度:中等)
随机推荐
SAP ABAP BAPI_MATERIAL_AVAILABILITY 查询可用库存
unity3d-射线
LeetCode精讲——676. 实现一个魔法字典(难度:中等)
硬件课程设计:基于STM32的多功能播放器之系统设计
联想词匹配-总结
[learning records on June 2]
Scope when multiple else if are nested
DDD——在我梦里,我还能让你把我给欺负了?
什么是eventloop(事件循环)?
【优先队列(堆)】二叉堆类模板的实现
Hardware course design: system design of multi-function player based on stm32
SAP ABAP Selection Screen 选择屏幕看这一篇就够了(持续更新)
Implementation of dynamic array vector class template
Programmer's daily skills
【6月2号学习记录】
unity3d-MonoBehaviour基类
Leetcode lecture - 676 Implement a magic Dictionary (difficulty: medium)
AVL树-带平衡条件的二叉查找树
128. 最长连续序列
LeetCode精讲——1217.玩筹码(难度:简单)