mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2026-02-02 18:39:09 +08:00
Merge branch 'master' into patch-17
This commit is contained in:
@@ -227,7 +227,6 @@ Java:
|
||||
class Solution {
|
||||
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
|
||||
return lowestCommonAncestor1(root, p, q);
|
||||
|
||||
}
|
||||
public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
|
||||
if (root == null || root == p || root == q) {
|
||||
@@ -246,6 +245,23 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
```java
|
||||
// 代码精简版
|
||||
class Solution {
|
||||
TreeNode pre;
|
||||
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
|
||||
if (root == null || root.val == p.val ||root.val == q.val) 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 && right != null) return right;
|
||||
else if (left != null && right == null) return left;
|
||||
else return null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
|
||||
@@ -258,4 +274,4 @@ Go:
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
||||
Reference in New Issue
Block a user