Skip to content

Commit a8fda8f

Browse files
author
Jeongwon Na
committed
lca solution
1 parent 42275af commit a8fda8f

File tree

1 file changed

+23
-0
lines changed
  • lowest-common-ancestor-of-a-binary-search-tree

1 file changed

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

0 commit comments

Comments
 (0)