Skip to content

Commit 43c4a66

Browse files
committed
#249 Lowest Common Ancestor of a Binary Search Tree
1 parent d57d334 commit 43c4a66

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
# Time Complexity: O(n)
3+
# Space Compleixty: O(1)
4+
*/
5+
6+
/**
7+
* Definition for a binary tree node.
8+
* public class TreeNode {
9+
* int val;
10+
* TreeNode left;
11+
* TreeNode right;
12+
* TreeNode(int x) { val = x; }
13+
* }
14+
*/
15+
16+
class Solution {
17+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
18+
// null check unnecessary
19+
20+
if (root.val > p.val && root.val > q.val) {
21+
return lowestCommonAncestor(root.left, p, q);
22+
} else if (root.val < p.val && root.val < q.val) {
23+
return lowestCommonAncestor(root.right, p, q);
24+
} else {
25+
return root;
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)