File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments