Skip to content

Commit

Permalink
Update 0236.二叉树的最近公共祖先.md
Browse files Browse the repository at this point in the history
添加 0236.二叉树的最近公共祖先 Java版本
  • Loading branch information
Joshua-Lu committed May 13, 2021
1 parent 1f5408b commit 001a4dc
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions problems/0236.二叉树的最近公共祖先.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,28 @@ public:
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;
}
}
```

Python:

Expand Down

0 comments on commit 001a4dc

Please sign in to comment.