From 3a5d2ec0e6bc01befbfa456320036f4bb606b0d9 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 18 Aug 2024 21:24:29 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB236.=20Lowest=20Common=20An?= =?UTF-8?q?cestor=20of=20a=20Binary=20Tree=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...west-common-ancestor-of-a-binary-tree.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 java/lowest-common-ancestor-of-a-binary-tree.java diff --git a/java/lowest-common-ancestor-of-a-binary-tree.java b/java/lowest-common-ancestor-of-a-binary-tree.java new file mode 100644 index 0000000..85ede21 --- /dev/null +++ b/java/lowest-common-ancestor-of-a-binary-tree.java @@ -0,0 +1,24 @@ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode node, TreeNode p, TreeNode q) { + if (node == null) { + return null; + } + + if (node.val == p.val || node.val == q.val) { + return node; + } + + var left = lowestCommonAncestor(node.left, p, q); + var right = lowestCommonAncestor(node.right, p, q); + + if (left == null) { + return right; + } + + if (right == null) { + return left; + } + + return node; + } +}