mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
25 lines
459 B
Java
25 lines
459 B
Java
|
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;
|
||
|
}
|
||
|
}
|