235. (LCA) Lowest Common Ancestor of a Binary Search Tree
Last updated
Last updated
ps. ้้ก็จ leetcode 236 ไนๅฏไปฅ่งฃๆฑบ, ้ๅบฆ้ๅทฎไธๅค...ไฝๅ ็บ้้กๆฏ BST, ๆไปฅไฝๆณๆด็ฐกๅฎ
/*
235. Lowest Common Ancestor of a Binary Search Tree
level: easy
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
BST LCA
ๅฆๆๅช็็ฅๅ
, ๆไปฅ 3, 5 ็ฅๅ
ๆ 6, 2, 4
ไฝๆ็ฎ็ lca, ไธๅฎๆ่ฎ 3, 5 ๅจๅทฆๅณๅ
ฉๅด
ๅ
ถไปๅฏไปฅ็ผ็พ, 3,5 ้ฝๅจ ๆไธๅด๏ผ6, 2 ็ๆไธๅด
ๅ ็บ bst ๆๅทฆๅฐๅณๅคง็็นๆง ๏ผๅทฆๅญๆจนๆๆ็ฏ้ป็ๅฐๆผroot, ๅณๅญๆจนๆๆ็ฏ้ป็ๅคงๆผroot
1. ๆไปฅpqๅๆๆฏroot ๅคงๆ, ไปฃ่กจpqๅจๅณ้, ๆไปฅ่ฆๅพๅณ่ตฐ
2. ๆไปฅpqๅๆๆฏroot ๅฐๆ, ไปฃ่กจpqๅจๅทฆ้, ๆไปฅ่ฆๅพๅทฆ่ตฐ
3. ๅ
ถไป็ๆณ, ไปฃ่กจๆพๅฐไบ, p qๅจๅทฆๅณๅ
ฉๅดไบ
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.
LCS:
ๅคๆทๆนๅผ: ๆพๅฐ LCS็ๆนๅผ p, q ไธๅจๆญค LCS ๅไธๅด
//่ชชๆ1
if (pVal > parentVal && qVal > parentVal) {
// ๅพๅณ่ตฐ๏ฝ๏ฝ
return lowestCommonAncestor(root.right, p, q);
} else if (pVal < parentVal && qVal < parentVal) { //่ชชๆ2
// ๅพๅทฆ่ตฐ๏ฝ๏ฝ
return lowestCommonAncestor(root.left, p, q);
} else {//่ชชๆ3
//ๆพๅฐไบ We have found the split point, i.e. the LCA node.
return root;
}
Time Complexity: O(N),
where N is the number of nodes in the BST. In the worst case we might
be visiting all the nodes of the BST.
Space Complexity: O(N). This is because the maximum amount of
space utilized by the recursion stack would be N since the height of a
skewed BST could be N
*/
public class LowestCommonAncestorBST {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
int parentVal = root.val;
int pVal = p.val;
int qVal = q.val;
if (pVal > parentVal && qVal > parentVal) {
return lowestCommonAncestor(root.right, p, q);
} else if (pVal < parentVal && qVal < parentVal) {
return lowestCommonAncestor(root.left, p, q);
} else { //terminator
return root;
}
}
}
```java
/**
* Definition for a binary tree node.
* 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) {
int value1 = Math.min(p.val, q.val);
int value2 = Math.max(p.val, q.val);
return dfs(root, value1, value2);
}
private TreeNode dfs(TreeNode node, int value1, int value2) {
if (node == null) {
return null;
}
if (node.val > value2) {
return dfs(node.left, value1, value2);
}
if (node.val < value1) {
return dfs(node.right, value1, value2);
}
// value1 <= node.val <= value2
return node;
}
}
```