Update 0236.二叉树的最近公共祖先.md

更新 0236题 Java版本代码
This commit is contained in:
zhicheng lee
2021-12-08 16:49:06 +08:00
committed by GitHub
parent 7199a4c82e
commit c5b691b91d

View File

@ -221,42 +221,30 @@ public:
## Java ## Java
```Java ```Java
class Solution { class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return lowestCommonAncestor1(root, p, q); if (root == null || root == p || root == q) { // 递归结束条件
}
public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root; 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
// 代码精简版
class Solution {
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 left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) return root;
else if (left == null && right != null) return right; if(left == null && right == null) { // 若未找到节点 p 或 q
else if (left != null && right == null) return left; return null;
else return null; }else if(left == null && right != null) { // 若找到一个节点
return right;
}else if(left != null && right == null) { // 若找到一个节点
return left;
}else { // 若找到两个节点
return root;
} }
} }
}
``` ```
## Python ## Python