Skip to content

Commit cd9aa95

Browse files
author
Li Li
committed
add code of 235
1 parent bcb0e8e commit cd9aa95

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

top-interview-questions/235. Lowest Common Ancestor of a Binary Search Tree.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// general one for BT not only BST
12
public class Solution {
23
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
34
if (root == null) return null;
@@ -8,4 +9,17 @@ public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
89
else if (left == null) return right;
910
else return left;
1011
}
12+
}
13+
14+
// specific for BST
15+
public class Solution {
16+
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
17+
if (root.val > p.val && root.val > q.val) {
18+
return LowestCommonAncestor(root.left, p, q);
19+
} else if (root.val < p.val && root.val < q.val) {
20+
return LowestCommonAncestor(root.right, p, q);
21+
} else {
22+
return root;
23+
}
24+
}
1125
}

0 commit comments

Comments
 (0)