给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6。
示例 2:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
输出: 2
解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
个人思路 :利用二叉树特性将p和q的祖先都找出来 最后找最大的公共祖先;
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p==root||q==root)
return root;
ArrayList<TreeNode> ancp=new ArrayList<TreeNode>();//p的祖先集合
ArrayList<TreeNode> ancq=new ArrayList<TreeNode>();//q的祖先集合
TreeNode temp=root;
ancp.add(root);
ancq.add(root);
while(temp!=p)
{
if(temp.val<p.val)
temp=temp.right;
else
temp=temp.left;
ancp.add(temp);
}
temp=root;
while(temp!=q)
{
if(temp.val<q.val)
temp=temp.right;
else
temp=temp.left;
ancq.add(temp);
}
for(int i=ancq.size()-1;i>-1;i--)
{
if(ancp.contains(ancq.get(i)))
return ancq.get(i);
}
return root;
}
}
递归解法:如果p和q同属root左子树或右子树 则以该节点为根继续找
若不同属一个子树 则该root便是最大公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// Value of current node or parent node.
int parentVal = root.val;
// Value of p
int pVal = p.val;
// Value of q;
int qVal = q.val;
if (pVal > parentVal && qVal > parentVal) {
// If both p and q are greater than parent
return lowestCommonAncestor(root.right, p, q);
} else if (pVal < parentVal && qVal < parentVal) {
// If both p and q are lesser than parent
return lowestCommonAncestor(root.left, p, q);
} else {
// We have found the split point, i.e. the LCA node.
return root;
}
}
}