From 001a4dc00f2441fdd8ed70bdd3304c022d6bfc85 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:12:21 +0800 Subject: [PATCH] =?UTF-8?q?Update=200236.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0236.二叉树的最近公共祖先 Java版本 --- .../0236.二叉树的最近公共祖先.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 17096d48..2908c5bb 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -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: