Skip to content

Commit 1aa0cf7

Browse files
committed
solve lowest common ancestor of a binary search tree
1 parent 0315a1a commit 1aa0cf7

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
public class Solution {
2+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3+
TreeNode node = root;
4+
while (node != null) {
5+
if (p.val < node.val && q.val < node.val) {
6+
node = node.left;
7+
} else if (node.val < p.val && node.val < q.val) {
8+
node = node.right;
9+
} else {
10+
return node;
11+
}
12+
}
13+
return null;
14+
}
15+
}

0 commit comments

Comments
 (0)