一.解法
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
要点:递归,树
Python,C++,Java都用了递归的方法。
由于是二叉搜索树,root左边所有的值都小于root的值,root右边所有的值都大于root的值。
所以如果p,q的值都小于root的值,就去root.left找,
如果p,q的值都大于root的值,就去root.right找
否则说明root就是最近公共祖先
二.Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val<root.val and q.val<root.val:
return self.lowestCommonAncestor(root.left,p,q)
elif p.val>root.val and q.val>root.val:
return self.lowestCommonAncestor(root.right,p,q)
else:
return root
三.C++实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p == root || q == root || p->val<root->val&&q->val>root->val || p->val > root->val&&q->val < root->val)
return root;
if (p->val < root->val&&q->val < root->val)
return lowestCommonAncestor(root->left, p, q);
return lowestCommonAncestor(root->right, p, q);
}
};
四.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) {
if(p.val<root.val&&q.val<root.val) return lowestCommonAncestor(root.left,p,q);
else if(p.val>root.val&&q.val>root.val) return lowestCommonAncestor(root.right,p,q);
else return root;
}
}