题意:
思路:
三种情况:
- 最小公共祖先为p节点,q是p的子树中的节点
- 最小公共祖先为q节点,p是q的子树中的节点
- p和q分布在最小公共子树的两边
利用二叉搜索树的性质,如果root值要是大于两个节点的值,说明还可以往root的左子树去探索,因为搜索二叉树的性质是中序遍历的结果递增。
如果root的值小于两个节点的值,可以向root的右子进行探索。
如果出现root的值等于p或者q,或者root在p和q之间的情况,说明就找到了最小的祖先。
代码:
/**
* 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(p.val > q.val)
{
TreeNode temp = p;
p = q;
q = temp;
}
TreeNode res = root;
while(res != null)
{
if(res.val < p.val && res.val < q.val)
{
res = res.right;
}
else if(res.val > p.val && res.val > q.val)
{
res = res.left;
}else
{
return res;
}
}
return res;
}
}