mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #101 from Joshua-Lu/patch-18
更新 0236.二叉树的最近公共祖先 Java版本
This commit is contained in:
@ -223,7 +223,32 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
```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) {
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
TreeNode left = lowestCommonAncestor1(root.left, p, q);
|
||||||
|
TreeNode right = lowestCommonAncestor1(root.right, p, q);
|
||||||
|
if (left != null && right != null) {// 左右子树分别找到了,说明此时的root就是要求的结果
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
if (left == null) {
|
||||||
|
return right;
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
```java
|
```java
|
||||||
|
// 代码精简版
|
||||||
class Solution {
|
class Solution {
|
||||||
TreeNode pre;
|
TreeNode pre;
|
||||||
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
|
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
|
||||||
@ -236,7 +261,6 @@ class Solution {
|
|||||||
else return null;
|
else return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user