From 3eeb58fffeecdb1b60ad552b61159282df4cc9e3 Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Thu, 23 Jul 2020 09:40:35 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9B=B8?= =?UTF-8?q?=E5=85=B3.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blogs/Algorithm/剑指 Offer/二叉树相关.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/blogs/Algorithm/剑指 Offer/二叉树相关.md b/blogs/Algorithm/剑指 Offer/二叉树相关.md index 84ff829..4397202 100644 --- a/blogs/Algorithm/剑指 Offer/二叉树相关.md +++ b/blogs/Algorithm/剑指 Offer/二叉树相关.md @@ -638,3 +638,19 @@ class Solution { } ``` +#### [68 - II. 二叉树的最近公共祖先](https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/) + +```java +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if(root == null || root == p || root == q) return root; + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + if(left == null && right == null) return null; // 1. + if(left == null) return right; // 3. + if(right == null) return left; // 4. + return root; // 2. if(left != null and right != null) + } +} +``` +