/**
DFS;p、q出现的情况有1 出现在root两侧(包含q=root或者p==root),此时root为所求
2 q、p在root左侧,此时递归(root.left,q,p)
3 q、p在root右侧,递归(root.right,q,p)
*/
//该递归还能简化代码行数
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
int root_val = root.val;
int p_val = p.val;
int q_val = q.val;
int max = p_val > q_val ? p_val : q_val;
int min = q_val < p_val ? q_val : p_val;
if(min <= root_val && max >= root_val){
return root;
}
return max < root_val ? lowestCommonAncestor(root.left,p,q) :
lowestCommonAncestor(root.right,p,q);
}
}
//思路相同,该法用的是迭代,空间没法一好
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(true){
if(p.val < root.val && q.val < root.val){
root = root.left;
}else if(p.val > root.val && q.val > root.val){
root = root.right;
}else{
break;
}
}
return root;
}
}
//递归
/**
* 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) {
if((q.val >= root.val && p.val <= root.val) ||
(q.val <= root.val && p.val >= root.val)){
return root;
}else if(q.val < root.val){
return lowestCommonAncestor(root.left,p,q);
}else{
return lowestCommonAncestor(root.right,p,q);
}
}
}
235(M). 二叉搜索树的最近公共祖先 (A)(A)
于 2023-09-24 14:23:49 首次发布