题目简介
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
给定一个二进制搜索树(BST),找到最近公共祖先(LCA)的两个给定节点的成就。
根据维基百科的定义:“最近公共祖先是定义两节点v和w之间最低的节点不具有V和W的后裔(我们允许一个节点有自己的后裔)。”
例如,最近的公共祖先(LCA)节点2和8是6。另一个例子是LCA节点2和4是2,因为一个节点可以是自己根据LCA的定义。
自己的解法
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p.val == root.val||q.val ==root.val)
return root;
while(true){
TreeNode leftroot =findCurrent(root, p);
TreeNode rightroot =findCurrent(root, q);
if(leftroot != null&&leftroot.val == q.val)
return leftroot;
else if(rightroot !=null&&rightroot.val == p.val)
return rightroot;
else if(leftroot != null&&rightroot != null&&leftroot.val == rightroot.val)
return leftroot;
p = leftroot;
q = rightroot;
}
}
public TreeNode findCurrent(TreeNode root, TreeNode p){
if(p.val == root.val)
return root;
if(root == null)
return root;
else{
TreeNode left = root.left;
TreeNode right = root.right;
if(left != null&&left.val == p.val)
return root;
else if(right !=null&&right.val == p.val)
return root;
else if(p.val <root.val)
return findCurrent(left,p);
else
return findCurrent(right,p);
}
}
}
Hot解法
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while ((root.val - p.val) * (root.val - q.val) > 0)
root = p.val < root.val ? root.left : root.right;
return root;
}
}