2025年-G10-Lc84-235.二叉搜索树的最低公共祖先-java版
1.题目描述
2.思路
思路1:
思路2:
思路3:
3.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) {
while(root!=null)
{
if(p.val>root.val && q.val>root.val)
//说明p,q的值都在右子树
{root=root.right;}
else if(p.val<root.val&&q.val<root.val)
{
root=root.left;
}
else
{
return root;
}
}
return null;
}
}
方法二:
/**
* 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) {
//1.基本情况:如果 root 为 null 或 root 是 p 或 q,返回 root(题目有说,允许节点是其自身的后代)
if(root==null||root==p||root==q)
{
return root;
}
//2. 递归查找左子树和右子树中的 LCA
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
// 3.如果左子树和右子树都返回非空结果,说明当前节点是 LCA(root)
if(right!=null&&left!=null)
{
return root;
}
// //4 否则,返回左子树或右子树中的非空结果
// return left!=null?left:right;
if(left!=null)
{
return left;
}
else
{
return right;
}
//3.
// while(root!=null)
// {
// if(p.val>root.val && q.val>root.val)
// //说明p,q的值都在右子树
// {root=root.right;}
// else if(p.val<root.val&&q.val<root.val)
// {
// root=root.left;
// }
// else
// {
// return root;
// }
// }
// return null;
}
}