1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00

java: add «236. Lowest Common Ancestor of a Binary Tree»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-18 21:24:29 +02:00
parent e8d15a5bfa
commit 3a5d2ec0e6
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -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;
}
}