Skip to content

Commit d04626d

Browse files
author
Li Li
committed
add code of 236 and fix bug on 235
1 parent dcfe996 commit d04626d

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22
public class Solution {
33
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
44
if (root == null) return null;
5-
if (root.val == p.val || root.val == q.val) return root;
5+
if (root == p || root == q) return root;
66
TreeNode left = LowestCommonAncestor(root.left, p, q);
77
TreeNode right = LowestCommonAncestor(root.right, p, q);
88
if (left != null && right != null) return root;
9-
else if (left == null) return right;
10-
else return left;
9+
return left == null ? right : left;
1110
}
1211
}
1312

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
public class Solution {
2+
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3+
if (root == null) return null;
4+
if (root == p || root == q) return root;
5+
TreeNode left = LowestCommonAncestor(root.left, p, q);
6+
TreeNode right = LowestCommonAncestor(root.right, p, q);
7+
if (left != null && right != null) return root;
8+
return left == null ? right : left;
9+
}
10+
}

0 commit comments

Comments
 (0)