Lowest Common Ancestor of a Binary Search Tree LeetCode solution in Java

1
/**
2
* Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode
3
* right; TreeNode(int x) { val = x; } }
4
*/
5
class Solution {
6
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
7
if (root == null || root == p || root == q) return root;
8

9
TreeNode left = lowestCommonAncestor(root.left, p, q);
10
TreeNode right = lowestCommonAncestor(root.right, p, q);
11

12
if (left == null) return right;
13
if (right == null) return left;
14
else {
15
return root;
16
}
17
}
18
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0