public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) { // 탐색할 노드 없거나, 둘 중 하나 찾은 경우
return root;
}
TreeNode leftNode = lowestCommonAncestor(root.left, p, q);
TreeNode rightNode = lowestCommonAncestor(root.right, p, q);
// 양쪽에서 노드를 찾으면 현재 root가 LCA
if (leftNode != null && rightNode != null) {
return root;
}
// 한쪽에서만 노드를 찾으면 그 노드가 LCA
return leftNode != null ? leftNode : rightNode;
}
}
We use recursion to search for both nodes p and q.
- Search left and right subtrees.
- If both left and right return a node, it means p and q are found in different branches → So the current root is the LCA.
- If only one side returns a node, it means both p and q are in the same subtree → So we return that node upward.
- If neither side finds anything, return null.
'자율 학습 > 스터디' 카테고리의 다른 글
Binary Tree (DFS, BFS) vs. Binary Search Tree (0) | 2025.04.06 |
---|---|
[LeetCode75] Find Peak Element (0) | 2025.04.01 |
[LeetCode 75] 700. Search in a Binary Search Tree (0) | 2025.03.28 |
[LeetCode 75] 215. Kth Largest Element in an Array (1) | 2025.03.25 |
[LeetCode] 2352. Equal Row and Column Pairs (0) | 2025.03.18 |