Skip to content

Commit 11c1853

Browse files
committed
add lowest common ancestor of a BST solution
1 parent 1b73552 commit 11c1853

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
class Solution {
11+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12+
13+
if (root == null || root == p || root == q) {
14+
return root;
15+
}
16+
17+
// 재귀로 좌측과 우측 탐색
18+
TreeNode left = lowestCommonAncestor(root.left, p, q);
19+
20+
TreeNode right = lowestCommonAncestor(root.right, p, q);
21+
22+
// 좌우 둘 다 null이 아니라면: 현재 root를 조상으로 하는 서브 트리에서 p와 q를 발견했음을 의미하므로 root가 공통 조상
23+
if (left != null && right != null) {
24+
return root;
25+
} else if (left != null) {
26+
return left;
27+
} else {
28+
return right;
29+
}
30+
31+
}
32+
}
33+

0 commit comments

Comments
 (0)