Update 递归.md

This commit is contained in:
移动开发小冉
2021-11-15 01:22:38 +08:00
committed by GitHub
parent 363cf82d54
commit 4a31531cf6
+18
View File
@@ -233,6 +233,24 @@ public static LinkedNode mergeSeqLink(LinkedNode l1, LinkedNode l2){
```Java
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// base case
if (root == null) return null;
if (root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
// 情况 1
if (left != null && right != null) {
return root;
}
// 情况 2
if (left == null && right == null) {
return null;
}
// 情况 3
return left == null ? right : left;
}
```