ðð 235. äºåæ玢æ çæè¿å ¬å ±ç¥å
2022幎10æ10æ¥
- algorithm
ðð 235. äºåæ玢æ çæè¿å ¬å ±ç¥å
éŸåºŠ: ðð
é®é¢æè¿°
è§£æ³ 1 - éçš
/**
* 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) {
// æè·¯ïŒ
// éåœ
return mySol(root, p, q);
}
private TreeNode mySol(TreeNode root, TreeNode p, TreeNode q) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return root;
}
// root != null
if(root == p || root == q) {
return root;
}
TreeNode left = mySol(root.left, p, q);
TreeNode right = mySol(root.right, p, q);
if(left == null && right == null) {
return null;
}
if(left != null && right != null) {
// 䞀䞪èç¹åå«åšå·Šå³åæ
return root;
}
if(left == null) {
return right;
}
return left;
}
}
èŸåº 1
è§£æ³ 2 - ç¹æ®
/**
* 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) {
// æè·¯ïŒ
// å©çšäºåæ玢æ°çç¹æ§
return mySol(root, p, q);
}
private TreeNode mySol(TreeNode root, TreeNode p, TreeNode q) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return root;
}
int min = Math.min(p.val, q.val);
int max = Math.max(p.val, q.val);
// æè¿å
Œ
񇝆
è¯å®åš [min, max] ä¹éŽ
if(root.val == min || root.val == max) {
return root;
}
if(root.val > min && root.val < max) {
return root;
}
if(root.val < min) {
// åŸå³åæ äžæŸ
return mySol(root.right, p, q);
}
return mySol(root.left, p, q);
}
}